结合select distinct和order by

时间:2014-01-28 14:07:15

标签: mysql sql union

这是我的SQL查询:

SELECT DISTINCT dest 
    FROM messages 
    WHERE exp = ? 
UNION 
SELECT DISTINCT exp 
    FROM messages 
    WHERE dest = ?

通过此查询,我收到了我发送或接收的所有邮件。但在我的messages表格中,我有一个字段timestamp,我需要通过此查询按时间戳添加订单...但是如何?

4 个答案:

答案 0 :(得分:2)

您可以在没有union的情况下执行此操作:

SELECT (case when exp = ? then dest else exp end), timestamp
FROM messages 
WHERE exp = ? or dest = ?;

然后,要为每位参与者获取最新消息,请使用group by而不是distinct

SELECT (case when exp = ? then dest else exp end) as other, max(timestamp)
FROM messages 
WHERE exp = ? or dest = ?
group by (case when exp = ? then dest else exp end)
order by max(timestamp) desc;

答案 1 :(得分:1)

SELECT *
FROM
    (   SELECT
           col1 = dest,
           col2 = MAX(timestampCol)
        FROM
            messages 
        WHERE 
            exp = ? 
        GROUP BY 
            dest
        UNION 
        SELECT
            col1 = exp,
            col2 = MAX(timestampCol)
        FROM
            messages 
        WHERE 
            dest= ? 
        GROUP BY 
            exp
    ) tbl
ORDER BY col2

这应该每distinct exp / dest只返回一行,但我确信这可能在没有联合的情况下完成; GROUP BY只能获得最新版本。

更新了SQL:鉴于一条记录上的exp可能在同一记录或另一条记录上等于dest

SELECT 
    CASE WHEN exp = ? THEN dest ELSE exp END AS col1  
    ,MAX(timestampCol) AS col2
FROM 
    messages 
WHERE 
    exp = ? 
    OR dest = ?
GROUP BY 
    (CASE WHEN exp = ? THEN dest ELSE exp END)
ORDER BY 
    MAX(timestampCol) DESC;

您可能需要考虑添加SQL Fiddle一些虚拟数据,以便用户更好地为您提供帮助。

答案 2 :(得分:0)

SELECT *
FROM
(
SELECT DISTINCT dest AS Column1, timestamp AS Column2
    FROM messages 
    WHERE exp = ? 
UNION 
SELECT DISTINCT exp AS Column1, timestamp AS Column2
    FROM messages 
    WHERE dest = ?
) tbl
ORDER BY Column2

答案 3 :(得分:0)

此查询将帮助您按时间戳

获取记录顺序
SELECT tbl.mailId, Max(timestampColumn) MostRecentDate
 FROM
    (
     SELECT exp AS mailId, Max(timestampCol) AS timestampColumn
     FROM Employeeatd 
     WHERE dest = ?  
     GROUP BY exp 
UNION 

     SELECT Dept AS abc, Max(timestampCol) AS timestampColumn
     FROM Employeeatd 
     WHERE exp = ?   
     GROUP BY Dept
    ) tbl
 GROUP BY mailId
 ORDER BY Max(timestampColumn) desc