MYSQL UNION DISTINCT

时间:2011-08-06 07:03:43

标签: mysql union distinct

我有两个选择,我目前正在成功运行UNION。

(SELECT a.user_id,a.updatecontents as city,b.country
FROM userprofiletemp AS a
LEFT JOIN userattributes AS b ON a.user_id=b.user_id
WHERE typeofupdate='city')

UNION DISTINCT

(SELECT a.user_id,c.city,c.country
FROM userverify AS a
LEFT JOIN userlogin AS b ON a.user_id=b.user_id
LEFT JOIN userattributes AS c ON a.user_id=c.user_id
WHERE b.active=1 AND a.verifycity=0);

结果如下:

100 Melbourne Australia
200 NewYork America
300 Tokyo Japan
100 Sydney Australia

catch是查询将带来重复的user_id(在本例中为100)。 第一个查询中的详细信息先于我,如果在第二个查询中重复user_id,我不需要它。

有没有办法让UNION成为列上的DISTINCT?在这种情况下user_id? 有没有办法进行上述调用而不是获取重复的user_id - 删除第二个。 我应该以不同的方式重新编写查询,而不是使用UNION。 真的希望它作为一个查询 - 如果需要,我可以使用SELECT和PHP来删除重复。

THX 亚当

3 个答案:

答案 0 :(得分:32)

没有。您无法指定需要与哪个确切的字段区分开来。它只适用于整行。

截至您的问题 - 只需将您的查询设为子查询,并在外部查询GROUP BY user_id

SELECT * FROM 
(SELECT a.user_id,a.updatecontents as city,b.country
FROM userprofiletemp AS a
LEFT JOIN userattributes AS b ON a.user_id=b.user_id
WHERE typeofupdate='city')

UNION DISTINCT

(SELECT a.user_id,c.city,c.country
FROM userverify AS a
LEFT JOIN userlogin AS b ON a.user_id=b.user_id
LEFT JOIN userattributes AS c ON a.user_id=c.user_id
WHERE b.active=1 AND a.verifycity=0) x
GROUP BY user_id

答案 1 :(得分:1)

(SELECT a.user_id,a.updatecontents as city,b.country
FROM userprofiletemp AS a
LEFT JOIN userattributes AS b ON a.user_id=b.user_id
WHERE typeofupdate='city')

UNION ALL

(SELECT a.user_id,c.city,c.country
FROM userverify AS a
LEFT JOIN userlogin AS b ON a.user_id=b.user_id
LEFT JOIN userattributes AS c ON a.user_id=c.user_id
WHERE b.active=1 AND a.verifycity=0
  AND a.user_id NOT IN
      ( SELECT user_id
        FROM userprofiletemp 
        WHERE typeofupdate='city'
      ) 
);

答案 2 :(得分:0)

MySQL UNION默认情况下会产生不同的行-但是,整个行需要是不同的。如果您希望将区别限制为一列或几列,因为其他列没有区别,那么一种实现方法是将UNION包装在子查询中,将GROUP BY包装在子查询中。通过您希望唯一的列进行子查询。

在这里,我将整个UNION包装在一个子查询中,给它一个别名,然后GROUP BY所需的唯一列:

SELECT * FROM (

SELECT a.user_id,a.updatecontents as city,b.country
FROM userprofiletemp AS a
LEFT JOIN userattributes AS b ON a.user_id=b.user_id
WHERE typeofupdate='city'

UNION

SELECT a.user_id,c.city,c.country
FROM userverify AS a
LEFT JOIN userlogin AS b ON a.user_id=b.user_id
LEFT JOIN userattributes AS c ON a.user_id=c.user_id
WHERE b.active=1 AND a.verifycity=0

) aa GROUP BY user_id;

如果您要在区分中包括多个列,请在GROUP BY之后列出它们,例如GROUP BY user_id, city


侧面注意:由于在这种情况下UNION不能提供理想的区别,因此简单地使用UNION显然是"UNION ALL is much faster than UNION"并没有好处,因此可以使用{ {1}},以加快查询速度。