查询优化 -- 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"
)
相关推荐
UFIT2 小时前
数据库操作
数据库·sql·oracle
柃歌7 小时前
【LeetCode Solutions】LeetCode 176 ~ 180 题解
数据结构·数据库·sql·算法·leetcode
vvilkim10 小时前
SQL语言基础:从入门到掌握结构化查询语言
数据库·sql·oracle
八股文领域大手子11 小时前
Spring Boot Controller 如何处理HTTP请求体
java·开发语言·sql·spring·spring cloud
多多*15 小时前
分布式ID设计 数据库主键自增
数据库·sql·算法·http·leetcode·oracle
我爱夜来香A15 小时前
SQL进阶:如何把字段中的键值对转为JSON格式?
数据库·sql·json
珹洺16 小时前
数据库系统概论(七)初识SQL与SQL基本概念
数据库·sql
鸿乃江边鸟17 小时前
Starrocks 的 ShortCircuit短路径
大数据·starrocks·sql
檀越剑指大厂20 小时前
【SQL系列】多表关联更新
数据库·sql
gadiaola1 天前
MySQL从入门到精通(三):MySQL数据类型、SQL语言—DDL
数据库·sql·mysql·database