Mysql Union实例_MySQL
程序员文章站
2022-05-20 09:07:13
...
前提,是每个查询结果集的列数要一样,类型要一样
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是全部累加一起。
推荐阅读
-
MySQL5.7完全卸载步骤详解
-
概述MySQL统计信息
-
mysql 5.7以上版本安装配置方法图文教程(mysql 5.7.12mysql 5.7.13mysql 5.7.14)
-
MySQL常见内存不足启动失败的完美解决方法
-
随机生成八位优惠码并保存至Mysql数据库
-
Mysql5.7中使用group concat函数数据被截断的问题完美解决方法
-
Mysql5.7.17 winx64.zip解压缩版安装配置图文教程
-
MySQL SQL语句分析与查询优化详解
-
Windows 64 位 mysql 5.7以上版本包解压中没有data目录和my-default.ini及服务无法启动的快速解决办法(问题小结)
-
解决mysql ERROR 1045 (28000)-- Access denied for user问题