说明:
UNION 操作符用于合并两个或多个 SELECT 语句的结果集。
请注意,UNION 内部的 SELECT 语句必须拥有相同数量的列。列也必须拥有相似的数据类型。同时,每条 SELECT 语句中的列的顺序必须相同。否则会报错。
union和 union all的关系和区别:
1.UNION ALL 命令和 UNION 命令几乎是等效的,不过 UNION ALL 命令会列出所有的值。
2.即 :union会对合并的两个或多个查询的结果集 进行 去重合并的操作。
union all则不会去重,只做合并,因此查出的结果集中 会有重复的记录。
示例:
分页查询sql
(
SELECT DISTINCT
c.u_id,
c.create_time
FROM
表A a
LEFT JOIN 表B b ON b.u_id = a.u_id
AND b.yn = 1
LEFT JOIN 表C c ON c.u_id = a.u_id
AND c.yn = 1
LEFT JOIN 表D d ON d.u_id = a.u_id
AND d.yn = 1
WHERE
1 = 1
AND a.yn = 1
AND b.vender_id IN ( 1 )
AND b.join_behavior = 1
AND b.store_join_type = 1
) UNION
(
SELECT DISTINCT
c.u_id,
c.create_time
FROM
表A a
LEFT JOIN 表B b ON b.u_id = a.u_id
LEFT JOIN 表C c ON c.u_id = a.u_id
LEFT JOIN 表D d ON d.u_id = a.u_id
WHERE
1 = 1
AND a.yn = 1
AND b.vender_id IN ( 1 )
AND b.join_behavior = 1
AND a.join_value IN ( 6 )
AND b.store_join_type = 2
)
ORDER BY
create_time DESC
LIMIT 0,200;
count统计sql:
select
COUNT(*)
FROM
(
( SELECT DISTINCT
c.u_id,
c.create_time
FROM
表A a
LEFT JOIN 表B b ON b.u_id = a.u_id
AND b.yn = 1
LEFT JOIN 表C c ON c.u_id = a.u_id
AND c.yn = 1
LEFT JOIN 表D d ON d.u_id = a.u_id
AND d.yn = 1
WHERE
1 = 1
AND a.yn = 1
AND b.vender_id IN ( 1 )
AND b.join_behavior = 1
AND b.store_join_type = 1
) UNION
(
SELECT DISTINCT
c.u_id,
c.create_time
FROM
表A a
LEFT JOIN 表B b ON b.u_id = a.u_id
AND b.yn = 1
LEFT JOIN 表C c ON c.u_id = a.u_id
AND c.yn = 1
LEFT JOIN 表D d ON d.u_id = a.u_id
AND d.yn = 1
WHERE
1 = 1
AND a.yn = 1
AND b.vender_id IN ( 1 )
AND b.join_behavior = 1
AND a.join_value IN ( 6 )
AND b.store_join_type = 2
)
)
AS temp