首页 >数据库 >mysql教程 >Mysql Union实例_MySQL

Mysql Union实例_MySQL

WBOY
WBOY原创
2016-06-01 13:12:201050浏览
前提,是每个查询结果集的列数要一样,类型要一样
SELECT g.goods_id FROM ( SELECT gr.`GOODS_ID`,COUNT(gr.`GOODS_ID`) num FROM rkgl_goods_repertory gr JOIN rkgl_repertory r ON r.`ID`=gr.`REPERTORY_ID` JOIN spgl_goods g ON g.`ID`=gr.`GOODS_ID` JOIN spgl_brand b ON b.`ID`=g.`BRAND_ID` JOIN spgl_goods_type gt ON gt.`ID`=g.`GOODS_TYPE_ID` WHERE r.`USER_ID`=36 AND g.`IS_DELETE`=FALSE AND gt.`IS_DELETE`=FALSE AND b.`IS_DELETE`=FALSE AND gr.`NUM`=0 GROUP BY gr.`GOODS_ID`) g WHERE g.num>1 UNION SELECT g.goods_id FROM ( SELECT gr.`GOODS_ID`,COUNT(gr.`GOODS_ID`) num FROM rkgl_goods_repertory gr JOIN rkgl_repertory r ON r.`ID`=gr.`REPERTORY_ID` JOIN spgl_goods g ON g.`ID`=gr.`GOODS_ID` JOIN spgl_brand b ON b.`ID`=g.`BRAND_ID` JOIN spgl_goods_type gt ON gt.`ID`=g.`GOODS_TYPE_ID` WHERE r.`USER_ID`=36 AND g.`IS_DELETE`=FALSE AND gt.`IS_DELETE`=FALSE AND b.`IS_DELETE`=FALSE AND gr.`NUM`=0 GROUP BY gr.`GOODS_ID`) g WHERE g.num=1

简单的实例就是

select * from a union select * from b


或者

(select * from a join b on a.id=b.a_id ) c union select * from d


还有一点就是UNION是过滤相同结果集求存不同结果集,而UNION ALL是全部累加一起。

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn