是否可以不使用union运算符组合sql中的查询结果(与union / union all相同)
答案 0 :(得分:4)
假设您有两个表格UNION
CREATE TABLE Table1
(`id` int, `name` varchar(32));
CREATE TABLE Table2
(`id` int, `name` varchar(32));
样本数据
表1:
| ID | NAME | |----|-------| | 1 | name1 | | 2 | name2 | | 3 | name3 |
表2:
| ID | NAME | |----|--------| | 11 | name11 | | 22 | name22 | | 33 | name33 | | 1 | name1 |
模仿UNION ALL
SELECT COALESCE(t1.id, t2.id) id,
COALESCE(t1.name, t2.name) name
FROM
(
SELECT TABLE_NAME <> 'table1' n
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = SCHEMA()
AND TABLE_NAME IN('table1', 'table2')
) t LEFT JOIN table1 t1
ON t.n = 0 LEFT JOIN table2 t2
ON t.n = 1
输出:
| ID | NAME | |----|--------| | 1 | name1 | | 2 | name2 | | 3 | name3 | | 11 | name11 | | 22 | name22 | | 33 | name33 | | 1 | name1 |
要模仿UNION
,您只需添加DISTINCT
SELECT DISTINCT COALESCE(t1.id, t2.id) id,
COALESCE(t1.name, t2.name) name
FROM
(
SELECT TABLE_NAME <> 'table1' n
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = SCHEMA()
AND TABLE_NAME IN('table1', 'table2')
) t LEFT JOIN table1 t1
ON t.n = 0 LEFT JOIN table2 t2
ON t.n = 1
输出:
| ID | NAME | |----|--------| | 1 | name1 | | 2 | name2 | | 3 | name3 | | 11 | name11 | | 22 | name22 | | 33 | name33 |
这是 SQLFiddle 演示
答案 1 :(得分:0)
我们尝试并获得了简单的查询,但我不知道这有多高效。
CREATE TABLE tableA
( col1 INTEGER , col2 INTEGER
);
CREATE TABLE tableB
( col1 INTEGER , col2 INTEGER
)
// insert statements
INSERT INTO tableA
(COL1, COL2
) VALUES
(12, 13
);
INSERT INTO tableA
(COL1, COL2
) VALUES
(14, 15
);
INSERT INTO tableB
(COL1, COL2
) VALUES
(12, 13
);
INSERT INTO tableB
(COL1, COL2
) VALUES
(14, 15
);
// for union all
SELECT (
CASE
WHEN b.col1 IS NULL
THEN a.col1
ELSE b.col1
END)
FROM
(SELECT COL1 FROM TableB
)b
FULL OUTER JOIN
(SELECT COL1 FROM TableA
) a
ON 1=2
// for union
SELECT (
CASE
WHEN b.col1 IS NULL
THEN a.col1
WHEN b.col1=a.col1
THEN b.col1
ELSE b.col1
END)
FROM
(SELECT COL1 FROM TableB
)b
FULL OUTER JOIN
(SELECT COL1 FROM TableA
) a
ON a.col1=b.col1