在两列

时间:2016-05-25 11:14:09

标签: sql distinct

我目前有一个查询,它使用union获取两列的不同值,但这只是在返回中显示1个字段,我想要做的是添加id(PK)列,以便我可以创建一个排序,这将允许最新的对话成为列表的首位。

SELECT DISTINCT  `to` 
FROM  `inbox` 
WHERE  `from` =  '$customer'
UNION 
SELECT DISTINCT  `from` 
FROM  `inbox` 
WHERE  `to` =  '$customer'

2 个答案:

答案 0 :(得分:2)

您的回答是UNION

SELECT DISTINCT `from`
FROM   `inbox`
WHERE  `from` = '$customer'
UNION
SELECT DISTINCT `to`
FROM   `inbox`
WHERE  `to` = '$customer'

UNION将两个选择输出合并为一个,忽略第二个输出的重复。

通过此查询可以解决获得最新会话的第二个问题:

SELECT `name`, MAX(`id`) id FROM
(
    SELECT `from` as `name`, `id`
    FROM   `inbox`
    WHERE  `from` = '$customer'
    UNION ALL
    SELECT `to` as `name`, `id`
    FROM   `inbox`
    WHERE  `to` = '$customer'
) DerivedTable
GROUP BY `name`
ORDER BY MAX(`id`)

答案 1 :(得分:1)

如果要添加其他列,则必须切换到GROUP BY而不是DISTINCT:

SELECT  -- return the "other" column  
   CASE WHEN `from` = '$customer' THEN `to` 
        WHEN `to` = '$customer' THEN `from` 
   END AS usr, 
   MAX(id) AS max_id
FROM  `inbox` 
WHERE `from` =  '$customer'
   OR `to` =  '$customer'
GROUP BY
--   CASE WHEN `from` = '$customer' THEN `to` 
--       WHEN `to` = '$customer' THEN `from` 
--   END
-- afaik MySQL allows using the alias usr instead
   usr
ORDER BY max_id DESC