从Union获得独特的价值

时间:2015-01-20 14:11:43

标签: mysql distinct union

情景:

Table A
MAPPING_ID    USER_TYPE    MODIFIED_ON
--------------------------------------

Table B
MAPPING_ID    ITEM_TYPE    MODIFIED_ON
--------------------------------------

我想在最后一分钟内获取修改过的记录[MAPPING_ID]

(SELECT mapping_id FROM A WHERE modified_on > date_sub(now(),interval 1 minute) 
UNION 
(SELECT mapping_id from B WHERE modified_on > date_sub(now(),interval 1 minute) 

但问题是,结果中可能有重复的mapping_id!如何在distinct上获得UNION mapping_id?

1 个答案:

答案 0 :(得分:2)

UNION默认删除重复行,除非您使用UNION ALL,请参阅http://dev.mysql.com/doc/refman/5.0/en/union.html

如果您想手动执行此操作:

SELECT DISTINCT * FROM (
(SELECT mapping_id FROM A WHERE modified_on > date_sub(now(),interval 1 minute) 
UNION 
(SELECT mapping_id from B WHERE modified_on > date_sub(now(),interval 1 minute) 
) subsub