SQL:过滤连接表

时间:2016-04-07 05:17:41

标签: sql

我有两个具有一对多关系的表,我想将一个遵循规则的查询放在一起,将'many'表中的特定行连接到'one'表中的一行。< / p>

用户表:

╔════╦══════════════╦
║ id ║  name        ║
╠════╬══════════════╬
║  1 ║ user 1       ║ 
║  2 ║ user 2       ║
║  3 ║ user 3       ║
║  4 ║ user 4       ║
╚════╩══════════════╩

消息表:

╔════╦══════════════╦═══════════╦═════════╗
║ id ║  Text        ║ user_id   ║   date  ║
╠════╬══════════════╬═══════════╬═════════╣
║  1 ║ Hello        ║    1      ║  3/31   ║
║  2 ║ World        ║    1      ║  4/1    ║
║  3 ║ Test message ║    2      ║  4/2    ║
║  4 ║ Another test ║    3      ║  4/4    ║
╚════╩══════════════╩═══════════╩═════════╝

我正在尝试从用户执行单个连接到消息以获取用户的最新消息。用户2将具有“测试消息”,用户3将具有“另一测试”。用户1是我无法弄清楚的 - 我希望用户1有一行返回'world',基于它具有最新日期的事实,但我没有看到有能力执行的连接在连接表上过滤。

4 个答案:

答案 0 :(得分:2)

尝试这样的事情:

SELECT
    message_id
    , [user_id]
    , name
    , [Text]
    , [date]
FROM
(
SELECT
    M.id AS message_id
    , U.id AS [user_id]
    , name
    , [Text]
    , [date]
    --Rank rows for each users by date
    , RANK() OVER(PARTITION BY M.[user_id] ORDER BY [date] DESC, M.id DESC) AS Rnk
FROM
    @messages AS M
    INNER JOIN
    @users AS U
        ON M.[user_id] = U.id
) AS Tmp
WHERE
    --The latest date
    Tmp.Rnk  = 1

此代码适用于SQL Server 2012及更高版本。

This code work in SQL Server 2012 and newer.

答案 1 :(得分:2)

您可以加入表格,然后过滤结果:

select tbl.name , tbl.Text from
(select User.name,
        Messages.Text,
        RANK() OVER (PARTITION BY User.name ORDER BY Messages.date desc) AS  rank  
from User inner join Messages 
on User.id = Messages.user_id) as tbl
where rank=1  

答案 2 :(得分:0)

让你入门的东西:

select u.id, u.name, m.text
from User u
inner join Messages m on m.user_id = u.id
inner join (
    select m.user_id, MAX(date) as max_date
    from User u
    inner join Messages m on m.user_id = u.id
    group by m.user_id
) t on t.user_id = m.user_id and m.date = t.max_date

答案 3 :(得分:0)

试试这个。它应该工作:

select user_ID,
text,
u.name,
max(date) from user u inner join messages m on m.user_id=u.id group by user_ID,
text,
u.name