查询优化 -- 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"
)
相关推荐
两点王爷7 小时前
面试 | 索引是什么?有哪些分类?索引为什么会失效?
sql·面试
codeejun1 天前
每日一Go·MySQL-20、SQL 性能调优实战总结
sql·mysql·golang
Decay__1 天前
PostgreSQL 用户权限与安全 —— 角色体系、GRANT 授权、pg_hba.conf 认证、行级安全与审计
运维·数据库·sql·postgresql
inferno2 天前
十三、存储过程(PROCEDURE)
数据库·sql·mysql
Decay__2 天前
PostgreSQL DBA 日常运维手册 —— 会话、锁阻塞、慢查询、膨胀与每日巡检
运维·数据库·sql·postgresql
kiwixing2 天前
GaussDB|几台机器、哪种协议:高可用部署形态与副本协议选型
数据库·sql·database·gaussdb
SongRenShuo2 天前
三年 MyBatis 排查史:从我翻日志,到让 SQL 自己浮现
sql·mybatis·idea·日志·调试
Decay__2 天前
PostgreSQL 安装部署实战 —— PGDG yum 源安装、initdb 初始化与 postgresql.conf 参数调优
运维·数据库·sql·postgresql
FungLeo3 天前
FengCMS · PHP+MySQL 升级实录 · 旧后台备份三宗罪:漏空表、改写内容、按分号切 SQL 直接执行
sql·mysql·php·安全加固·fengcms
ZhengEnCi4 天前
覆盖索引是什么:用借书和外卖看懂回表这件事
sql·mysql·postgresql