mysql查询统一2列

时间:2012-02-07 15:58:42

标签: mysql

我有一个包含4列(id,发件人,收件人,状态)的朋友,我需要一个可以统一(重聚,我不知道英文单词)发件人和收件人列的查询。 例如,表格如下所示

| sender | receiver |
|    2   |   10     |
|    2   |    8     |
|    2   |    9     |
|    6   |    2     |
|    7   |    3     |

查询应该只给出发送方和接收方的唯一ID。 (2,3,6,7,8,10)

2 个答案:

答案 0 :(得分:4)

这听起来像是union的工作:

select sender as id from <table_name>
union
select receiver as id from <table_name>

请注意,union会删除重复项(如果您想保留重复项,请使用union all。)

答案 1 :(得分:2)

SELECT DISTINCT a.iResult
FROM
    (SELECT sender as iResult FROM tableName
        UNION
     SELECT receiver as iResult FROM tableName) a
ORDER BY iResult ASC

返回

2
3
6
7
8
9
10

OR

SELECT GROUP_CONCAT(b.iResult)
     (SELECT DISTINCT a.iResult
     FROM
             (SELECT sender as iResult FROM tableName
                 UNION
              SELECT receiver as iResult FROM tableName) a
         ORDER BY iResult ASC) b

返回

2,3,6,7,8,9,10