我需要从一个表中返回所有值,然后将此表连接到另一个查询而不重复值。这是我目前的询问。
CREATE TABLE tmp_tbl (Id INT(11) PRIMARY KEY, Per VARCHAR(30), Des VARCHAR(50), Rol INT(11));
INSERT INTO tmp_tbl(Id, Per, Des, Rol)
SELECT DISTINCT
p.p_id AS Id,
p.p_title AS Per,
p.p_description AS Des,
'' AS Rol
FROM perm p;
SELECT
p.p_id AS Id,
p.p_title AS Per,
p.p_description AS Des,
r.id AS Rol
FROM perm p
LEFT JOIN roles rp
ON p.p_id = rp.p_id
INNER JOIN rol r
ON r.id = rp.r_id AND rp.r_id IN (101)
UNION ALL
SELECT * FROM
tmp_tbl;
DROP TABLE tmp_tbl;
该语句返回第一个select中的所有行,但是从第二个select语句复制了union上的行。
答案 0 :(得分:1)
尝试更换
UNION ALL
与
UNION
union all
不会删除重复项。
答案 1 :(得分:0)
您应该使用UNION
,而不是UNION ALL
实际上UNION
删除了重复记录(结果中的所有列都相同),UNION ALL
没有。
答案 2 :(得分:0)
使用UNION DISTINCT
确保:
(SELECT p.p_id AS Id, p.p_title AS Per, p.p_description AS Des, r.id AS Rol
FROM perm p
LEFT JOIN roles rp ON p.p_id = rp.p_id
INNER JOIN rol r ON r.id = rp.r_id AND rp.r_id IN (101))
UNION DISTINCT
(SELECT * FROM tmp_tbl);