简体   繁体   中英

Select distinct from two column

My database like this: table name: messages

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

And i am trying to get all unique id's from each table. So my answer must be 1, 3, 4, 5, 6.

if i use SELECT DISTINCT receive FROM messages ; i will get 1, 3 ,4

if i use SELECT DISTINCT transmit FROM messages ; i will get 1, 3 ,5, 6

how do i get 1, 3, 4, 5, 6?

The default for UNION is DISTINCT :

SELECT "from" FROM tableX 
UNION
SELECT "to" FROM tableX;
SELECT DISTINCT `fr_om` FROM `table`
UNION
SELECT DISTINCT `to` FROM `table` WHERE `to` NOT IN (SELECT DISTINCT `fr_om` FROM table)

Updated : you can just use UNION to remove the duplicates from your result set.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM