mysql多张无关联表查询数据并分页

Mysql 发表时间:2021-07-08 10:07:35 作者:梁子亮 浏览次数:1147

示例1

$sql = 'select * FROM( (select id,name,create_time,sort from `ar_card`) UNION ALL (select id,title,create_time,-1 from `ar_article`) ) as fnd where name like "%次%" order by create_time DESC limit 10,10';
$re = Db::query($sql);
print_dump($re);die;

注意,表1字段列数要与表2的字段列数相同,且表1的字段必须在表中存在(表2的字段可以不存在),若要区分结果是哪来自个表的,可以取表1存在但表2不存在的sort字段,再union all 表2后写死为一个异常的值(例如-1),则可以判断sort=-1即表示数据来自表2

示例2

$sql = 'select * FROM( (select id,shop_id,type,price,create_time,is_finish from `ar_rentdeduct`) UNION ALL (select id,shop_id,type,price,create_time,-1 from `ar_rentrecharge`) ) as fnd where (is_finish != -1 and type = 2) or (is_finish = -1 and type = 2) order by create_time DESC';
$re = Db::query($sql);
print_dump($re);die;

上一篇   mysql优化