查询优化 -- UNION 用法

union 不返回重复行(所有字段值相同的行)

union all 返回所有行

// 每类最多统计100条

sql 复制代码
select `server_id`,count(1) as logs from ( SELECT `server_id` FROM `log` WHERE `log`.`type` = "a" AND server_id=1 limit 100 )
UNION
select `server_id`,count(1) as logs from ( SELECT `server_id` FROM `log` WHERE `log`.`type` = "a" AND server_id=2 limit 100 )
UNION
select `server_id`,count(1) as logs from ( SELECT `server_id` FROM `log` WHERE `log`.`type` = "a" AND server_id=3 limit 100 );
sql 复制代码
SELECT * FROM log WHERE type="a"
UNION
SELECT * FROM log WHERE type="b"
UNION
SELECT * FROM log WHERE type="c"
order by id desc LIMIT 10

【高性能mysql】

sql 复制代码
(SELECT * FROM log WHERE type="a" order by id desc LIMIT 10)
UNION ALL
(SELECT * FROM log WHERE type="b" order by id desc LIMIT 10)
UNION ALL
(SELECT * FROM log WHERE type="c" order by id desc LIMIT 10)
order by id desc LIMIT 10
sql 复制代码
select sum(num)
from
(
SELECT count(1) as num FROM log WHERE type="a"
UNION
SELECT count(1) as num FROM log WHERE type="b"
UNION
SELECT count(1) as num FROM log WHERE type="c"
)
相关推荐
Flerken1015 小时前
数据库语言、SQL语言、数据库系统提供的两种语言
数据库·sql·oracle
掘根5 小时前
【网络】高级IO——poll版本TCP服务器
网络·数据库·sql·网络协议·tcp/ip·mysql·网络安全
小哇6666 小时前
Spring Boot,在应用程序启动后执行某些 SQL 语句
数据库·spring boot·sql
isNotNullX7 小时前
如何用SQL Server和Oracle进行数据同步?
大数据·数据库·sql·oracle
惜.己15 小时前
MyBatis中一对多关系的两种处理方法
java·开发语言·后端·sql·mysql·mybatis·idea
终末圆15 小时前
MyBatis动态SQL中的`if`标签使用【后端 19】
java·数据结构·数据库·sql·算法·spring·mybatis
andrew_121917 小时前
腾讯 IEG 游戏前沿技术 一面复盘
java·redis·sql·面试
andrew_121917 小时前
腾讯 IEG 游戏前沿技术 二面复盘
后端·sql·面试
Aa134517650251 天前
c#中使用sql防注入方式写入数据
数据库·sql·c#
OceanSky61 天前
Mybatis中sql数组为空判断
数据库·sql·mybatis·数组判空