根据另一个表从一个表中选择唯一行,然后对其进行排序

时间:2016-10-21 17:31:10

标签: mysql sql

我有两张桌子:

communications:
--------------------------------------------------
id  |   subject     |   timestamp   |   starter
--------------------------------------------------

messagepartners
-------------------------------------------------
id  |   commid      |   userid  |   type
-------------------------------------------------

messagepartners表存储参与对话的用户的ID(存储在通信表中)。 messagepartners中的列commid存储相应的通信id(通信中的列id)

对于id为userid的特定用户,我想获取userid参与的通信列表。该列表不应包含重复项,并按时间戳排序。

我该如何为此编写SQL查询? 感谢

2 个答案:

答案 0 :(得分:1)

采取步骤

这是一种加入表的方法

SELECT *
FROM communications as c
JOIN messagepartners as p on c.id = p.commid

按用户ID过滤

SELECT *
FROM communications as c
JOIN messagepartners as p on c.id = p.commid
WHERE p.userid = X

我们想要的数据

SELECT c.id, c.subject, c.timestamp
FROM communications as c
JOIN messagepartners as p on c.id = p.commid
WHERE p.userid = X

没有重复

SELECT DISTINCT c.id, c.subject, c.timestamp
FROM communications as c
JOIN messagepartners as p on c.id = p.commid
WHERE p.userid = X

我建议您运行这些步骤,并了解为什么要获得每一步所做的结果。

答案 1 :(得分:0)

以下查询执行您想要的操作:

SELECT 
    b.*
FROM
    (
        SELECT
            commid
        FROM
            messagepartners
        WHERE 
            userid = 1234
        GROUP BY
            commid
    ) a
    INNER JOIN communications b ON (a.commid = b.id)
ORDER BY
    B.timestamp
;

不要忘记用用户ID替换1234。