查询优化 -- 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"
)
相关推荐
鸿乃江边鸟2 天前
向量化和列式存储
大数据·sql·向量化
懒虫虫~3 天前
通过内存去重替换SQL中distinct,优化SQL查询效率
java·sql·慢sql治理
逛逛GitHub3 天前
1 个神级智能问数工具,刚开源就 1500 Star 了。
sql·github
Huhbbjs3 天前
SQL 核心概念与实践总结
开发语言·数据库·sql
咋吃都不胖lyh3 天前
SQL-字符串函数、数值函数、日期函数
sql
sensenlin913 天前
Mybatis中SQL全大写或全小写影响执行性能吗
数据库·sql·mybatis
xqlily3 天前
SQL 数据库简介
数据库·sql
森林-3 天前
MyBatis 从入门到精通(第三篇)—— 动态 SQL、关联查询与查询缓存
sql·缓存·mybatis
小虾米vivian3 天前
达梦:将sql通过shell脚本的方式放在后台执行
服务器·数据库·sql