SQL,从两个表中选择SELECT而不获取所有行

时间:2013-06-27 07:30:16

标签: sql select

我有两张表:COMMENTCOMMENTHISTORY

现在我需要从两个表中选择单元格,如下所示:

SELECT c.Id, c.Userid, ch.Text, ch.Timestamp
FROM COMMENT c, COMMENTHISTORY ch
WHERE ch.CommentId = c.Id
ORDER BY ch.Timestamp DESC

工作正常。唯一的问题是COMMENTHISTORY每个COMMENT有几行,因此SELECT最终会为每条评论检索多行。

我需要的是为每条评论检索一行。 ch.Text和ch.Timestamp与最新的相关COMMENTHISTORY行匹配的行。

关于如何做到这一点的任何想法?

感谢。

9 个答案:

答案 0 :(得分:1)

这将解决您的问题

SELECT c.Id, c.Userid, ch.Text, ch.Timestamp
FROM COMMENT c LEFT JOIN COMMENTHISTORY ch on C.ID = ch.comment_id
WHERE ch.CommentId = c.Id
GROUP BY c.id
ORDER BY ch.Timestamp DESC

答案 1 :(得分:0)

SELECT c.Id, c.Userid, ch.Text, max(ch.Timestamp)
FROM COMMENT c, COMMENTHISTORY ch
WHERE ch.CommentId = c.Id
GROUP BY C.ID, c.userid, ch.text

答案 2 :(得分:0)

这可能会对您有所帮助:

SELECT c.Id, c.Userid, ch.Text, ch.Timestamp
FROM COMMENT c LEFT JOIN COMMENTHISTORY ch ON ch.CommentId = c.Id
ORDER BY ch.Timestamp DESC

答案 3 :(得分:0)

使用此:

SELECT c.Id, c.Userid, Max(ch.Text), max(ch.Timestamp)
FROM COMMENT c, COMMENTHISTORY ch
WHERE ch.CommentId = c.Id
GROUP BY C.ID, c.Userid
ORDER BY ch.Timestamp DESC

答案 4 :(得分:0)

  SELECT c.Id, c.Userid, max(ch.Timestamp),max(ch.text)
    FROM COMMENT c, COMMENTHISTORY ch
    WHERE ch.CommentId = c.Id
    Group By  c.Id, c.Userid
    ORDER BY ch.Timestamp DESC

答案 5 :(得分:0)

此查询将为给定评论ID的最新记录选择最后CommentHisotry条记录:

WITH LastComment AS
(
    SELECT CH.CommentId, MAX(CH.Timestamp) as Date
    FROM COMMENTHISTORY CH
    GROUP BY CH.CommentId
)

SELECT c.Id, c.Userid, ch.Text, ch.Timestamp
FROM COMMENT c
INNER JOIN LastComment lc ON LC.CommentId = c.Id
INNER JOIN COMMENTHISTORY ch ON ch.CommentId = lc.CommentId and ch.TimeStamp = lc.Date
ORDER BY ch.Timestamp DESC

答案 6 :(得分:0)

尝试使用内部联接并将条件放在Where子句中。欲了解更多信息,请查看:Joins selection diagram

答案 7 :(得分:0)

查询:

SELECT c.Id, 
       c.Userid, 
       ch.Text, 
       ch.Timestamp
FROM COMMENT c
INNER JOIN COMMENTHISTORY ch
  ON ch.CommentId = c.Id
WHERE ch.Timestamp = (SELECT MAX(ch2.Timestamp)
                      FROM COMMENTHISTORY ch2
                      WHERE ch2.CommentId = c.Id )
ORDER BY ch.Timestamp DESC

答案 8 :(得分:0)

应该这样做......

;WITH CTE AS
(
    SELECT  ch.CommentId, ch.Text, ch.TimeStamp, ROW_NUMBER() OVER (PARTITION BY     ch.CommentId ORDER BY ch.TimeStamp DESC) RowNum
    FROM    COMMENTHISTORY ch
)
SELECT          c.Id, c.Userid, CTE.Text, CTE.TimeStamp
FROM            COMMENT c
    INNER JOIN  CTE ON c.Id = CTE.CommentId
WHERE           RowNum = 1