选择最大值

时间:2016-02-26 15:17:53

标签: sql max innodb

我很难找到一种方法来获取查询中每行的最大值。 我的查询看起来像这样:

SELECT f.FID, f.name, f.description, t.TID, t.topic, p.timestamp, u.username, u.ID
FROM forum f 
LEFT JOIN threads t ON t.FID=f.FID AND t.TID=(SELECT p.TID FROM posts p WHERE p.timestamp=(SELECT MAX(p.timestamp) FROM posts p))
LEFT JOIN posts p ON p.TID=t.TID
LEFT JOIN users u ON u.ID=p.authorID

一些简单的解释:每个帖子都绑定到一个帖子的TID,每个帖子都绑定到论坛的FID。 我想要做的是从每个论坛获取最新帖子(时间戳的最高值),但我有点卡在这里。 它是如何在当前状态下看起来的图片: forum image

2 个答案:

答案 0 :(得分:0)

执行此操作的一种方法是使用包含每TID个最大时间戳值的派生表的附加连接:

SELECT f.FID, f.name, f.description, t.TID, t.topic, 
       p.timestamp, u.username, u.ID
FROM forum f 
LEFT JOIN threads t ON t.FID = f.FID 
LEFT JOIN (
   SELECT TID, MAX(timestamp) AS max_timestamp
   FROM posts
   GROUP BY TID
) AS x ON t.TID = x.TIP
LEFT JOIN posts p ON p.TID = t.TID AND p.timestamp = x.max_timestamp
LEFT JOIN users u ON u.ID = p.authorID

答案 1 :(得分:0)

首先,我建议使用内部加入。然后我们可以为每个主题或论坛确定最后一篇文章(请参阅lp)并将其用作过滤器。

每个帖子的最后帖子:

SELECT
    f.FID, f.name, f.description, t.TID, t.topic, p.timestamp, u.username, u.ID
FROM forum f
INNER JOIN threads t ON t.FID=f.FID
INNER JOIN posts p ON p.TID=t.TID
INNER JOIN users u ON u.ID=p.authorID
INNER JOIN (
    SELECT TID, MAX(timestamp) AS timestamp
    FROM posts
    GROUP BY TID
) lp ON lp.TID = t.TID AND lp.timestamp = p.timestamp

每个论坛的最后帖子:

SELECT
    f.FID, f.name, f.description, t.TID, t.topic, p.timestamp, u.username, u.ID
FROM forum f
INNER JOIN threads t ON t.FID=f.FID
INNER JOIN posts p ON p.TID=t.TID
INNER JOIN users u ON u.ID=p.authorID
INNER JOIN (
    SELECT ft.FID, MAX(fp.timestamp) AS timestamp
    FROM posts fp
    INNER JOIN threads ft ON fp.TID=ft.TID
    GROUP BY ft.FID
) lp ON lp.FID = f.FID AND lp.timestamp = p.timestamp