最近也是在写项目中碰到的这个问题,需要将两个SELECT查询结果组合起来进行分组排序,想到了用union方法,用TP的union操作根本无法完成复杂的union操作,于是搜罗了一下,先说一下union的用法,在说一下TP中如何实现复杂的union操作。
一、UNION 用法
一 UNION语法
SELECT ... UNION[ALL | DISTINCT] SELECT ... [UNION [ALL | DISTINCT] SELECT ...]
(SELECT a FROM tbl_name WHERE a=10 AND B=1)UNION(SELECT a FROM tbl_name WHERE a=11 AND B=2)ORDER BY a LIMIT 10; (SELECT a FROM tbl_name WHERE a=10 AND B=1)UNION(SELECT a FROM tbl_name WHERE a=11 AND B=2)ORDER BY a LIMIT 10;
(SELECT a AS b FROM t) UNION (SELECT ...) ORDER BY b; (SELECT a AS b FROM t) UNION (SELECT ...) ORDER BY a; To apply ORDER BY or LIMIT to an individual SELECT, place the clause inside the parentheses that enclose the SELECT。
(SELECT a FROM tbl_name WHERE a=10 AND B=1 ORDER BY a LIMIT 10)UNION(SELECT a FROM tbl_name WHERE a=11 AND B=2 ORDER BY a LIMIT 10);
( SELECT * FROM `blog` WHERE top=1 ORDER BY created DESC ) UNION ( SELECT * FROM `blog` WHERE top = 0 ORDER BY created DESC ) LIMIT 2 , 3
二、TP中复杂的UNION 写法
如,要实现如下基础union写法
(SELECT a...)UNION(SELECT a...) ORDER BY a LIMIT 0,5
$sql1 = $model ->field('id,name') ->table('tablename') ->group('field') ->where($where) ->buildSql(); $sql2 = $model ->field('id,name') ->table('tablename') ->group('field') ->where($where) ->buildSql(); $sql=$sql1.'UNION'.$sql2.' ORDER BY id DESC LIMIT '.$limit.','.$pageLen;//最终SQL语句 $result=$model->query($sql);
先用TP自带的buildSql()方法转化成原生SQL语句,然后在UNION两个SQL语句就可以得到我们想要的最终结果了。
【参考】TP查询语言
mysql union用法