选择与两列不同

时间:2014-05-12 20:08:23

标签: php mysql sql

我的数据库如下:表名:消息

| receive | transmit |
---------------------
|   1    |  5    |
|   1    |  6    |
|   1    |  3    |
|   3    |  1    |
|   4    |  1    |
|   2    |  3    |
|   4    |  6    |
|   7    |  9    |

我正试图从每张桌子中获取所有唯一身份证。所以我的回答必须是1,3,4,5,6。

如果我使用SELECT DISTINCT receive FROM messages ;,我将获得1,3,4

如果我使用SELECT DISTINCT transmit FROM messages ;,我将获得1,3,5,6

我如何获得1,3,4,5,6?

2 个答案:

答案 0 :(得分:5)

UNION的默认值为DISTINCT

SELECT "from" FROM tableX 
UNION
SELECT "to" FROM tableX;

答案 1 :(得分:2)

SELECT DISTINCT `fr_om` FROM `table`
UNION
SELECT DISTINCT `to` FROM `table` WHERE `to` NOT IN (SELECT DISTINCT `fr_om` FROM table)

已更新:您只需使用UNION即可从结果集中删除重复项。

SELECT DISTINCT `fr_om` FROM `table`
UNION
SELECT DISTINCT `to` FROM `table`