PHP& Mysql - 两个表之间的左外连接

时间:2010-11-24 14:58:30

标签: php mysql left-join polymorphic-associations

我有两个名为'events'和'topics'的表,每个表可以有很多注释。

我需要做的是列出所有事件和主题以及每行的注释量。我已经设法返回所有主题,这很好但我不知道如何将事件表添加到MySql。注释和事件表字段如下所示。任何人都可以帮我解决这个问题吗?

活动:

  • ID
  • EVENT_NAME

评论:

  • post_id< - 事件或主题表的相关ID
  • table< - 该行所属的表,无论是主题还是事件

    SELECT 
      t.id, t.title, c.created_at, 
      IF(ISNULL(c.allComments), 0, c.allComments) AS totalComments
    FROM topics AS t
    LEFT OUTER JOIN (
        SELECT created_at, post_id, COUNT(*) AS allComments 
        FROM comments
        GROUP BY post_id
    ) AS c ON c.post_id = t.id
    ORDER BY tc.created_at DESC, c.allComments DESC
    

4 个答案:

答案 0 :(得分:1)

听起来像事件和主题应该是同一个表。

不过,我认为我们可以通过UNION来做到这一点。我希望事件和主题有相同的列? (或者至少是同样重要的那些?)

(SELECT c.table as event_or_topic, e.*, count(C.table), MAX(C.created_at) as latest_c
FROM events E LEFT JOIN comments C on (C.post_id = E.id)
WHERE C.table = 'Events' 
GROUP BY C.post_id)
UNION
(SELECT c.table as event_or_topic, t.id*, count(C.table), MAX(C.created_at) as latest_c
FROM topics T LEFT JOIN comments C on (C.post_id = E.id)
WHERE C.table = 'Topics' 
GROUP BY C.post_id)
ORDER BY latest_c

请注意,ORDER BY适用于整个UNION,而不是单个SELECT。

使用LEFT JOIN应该允许那些没有评论的行仍然显示。我认为问题在于我们的部分选择依赖于评论(即 - C.table,最后评论的排序等)。计数应该没问题 - 如果没有评论就会为零。

您可能需要稍微更改SELECT部分​​。我想显示C.table,所以你知道一行是一个主题还是一个事件,但我担心它可能搞砸了。除了伯爵之外,你还需要评论吗?您在查询中使用了除post_id和table之外的一些列,而忽略了在您的问题中解释。

你还有列我不知道它们是什么,比如评论的zoneTable

答案 1 :(得分:0)

试试这个:

SELECT t.id, t.title, c.created_at, COUNT(c.allComments) AS totalComments FROM topics AS t LEFT JOIN comments c ON t.id=c.post_id GROUP BY t.id ORDER BY tc.created_at DESC, c.allComments DESC

答案 2 :(得分:0)

如果我理解你的问题,你有3个表:

-Events

-Topics

-Comments

如果确实如此,那么应该提取所有数据:

SELECT *
FROM events,topics
LEFT JOIN comments ON post_ID = ID
ORDER BY date DESC

希望我的方向正确!

W上。

答案 3 :(得分:0)

我已经开始工作了。如果有人知道更好,更有效的方法,那么请告诉我:

(SELECT t.id, t.title, tc.dateCreated AS commentDate, 
IF(ISNULL(tc.allComments), 0, tc.allComments) AS totalComments,
t.LastActive as dateChanged
    FROM Events AS t
    LEFT OUTER JOIN (
          SELECT MAX(created_at) AS dateCreated, post_id,
          COUNT(*) AS allComments 
          FROM comments
          GROUP BY post_id
          ) AS tc ON tc.post_id = t.id)
UNION
(SELECT t.id, t.title, tc.dateCreated AS commentDate, 
IF(ISNULL(tc.allComments), 0, tc.allComments) AS totalComments,
t.LastActive as dateChanged 
    FROM topics AS t
    LEFT OUTER JOIN (
          SELECT MAX(created_at) AS dateCreated, post_id,
          COUNT(*) AS allComments 
          FROM comments
          GROUP BY post_id
          ) AS tc ON tc.post_id = t.id)
ORDER BY commentDate DESC, dateChanged DESC, totalComments DESC