Mysql Union两个表具有不同的值

时间:2012-07-05 07:25:54

标签: mysql select union no-duplicates

我需要从一个表中返回所有值,然后将此表连接到另一个查询而不重复值。这是我目前的询问。

    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上的行。

3 个答案:

答案 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);