dsxay48646 2013-09-11 13:49
浏览 22
已采纳

选择组合Join和Count的行

I am building a simple Question/Reply system using php and mysql.
What i am trying to do is display all questions, among with their replies count and the timestamp of the last reply.
Here is the structure of my tables:

Table 'Discussion':  
id | title | description | user_id | timestamp
--------------------------------------------------------------------------------
Table 'Reply':  
id | reply_text | user_id | discussion_id | timestamp

What i'm doing right now is select the discussions and get the replies count like this:

SELECT 
     d.*,
     count(dr.id) AS replies_count
FROM discussion d
LEFT JOIN discussion_reply dr ON d.id = dr.discussion_id
GROUP BY d.id

This returns rows like id | title | description | user_id | timestamp | replies_count

Then (via PHP) I loop over the results and query the DB to get the reply with the most recent (max) timestamp for each discussion.
So, for every row returned by the first query, a new query is made.

Is there a way to get all the info i need, just by executing one query?
Like modify my initial query so that it returns:

id | title | description | user_id | timestamp | replies_count | latest_reply_timestamp

Thank you in advance

  • 写回答

1条回答 默认 最新

  • doupinwan0563 2013-09-11 13:52
    关注

    The statement below will give you the latest reply in every discussion.

    SELECT  a.id, a.title, a.description, a.user_id, a.timestamp,
            b.id ReplyID, b.reply_text, b.user_id, b.discussion_id, 
            b.timestamp ReplyTimestamp,
            COALESCE(c.totalReplies, 0) TotalReplyCount
    
    FROM    Discussion a
            LEFT JOIN
            (
                SELECT  a.*
                FROM    Reply a
                        INNER JOIN
                        (
                            SELECT  discussion_id, MAX(timestamp) timestamp
                            FROM    Reply
                            GROUP   BY discussion_id
                        ) b ON  a.discussion_id = b.discussion_id AND
                                a.timestamp = b.timestamp
            ) b ON  a.discussion_id = b.discussion_id
            LEFT JOIN
            (
                SELECT  discussion_id, COUNT(*) totalReplies
                FROM    Reply
                GROUP   BY discussion_id    
            ) c ON a.discussion_id = c.discussion_id
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号