MySQL Multiple Left Joins

前端 未结 2 1219
春和景丽
春和景丽 2020-12-13 01:31

I am trying to create a news page for a website I am working on. I decided that I want to use correct MySQL queries (meaning COUNT(id) and joins instead of more than one que

相关标签:
2条回答
  • 2020-12-13 02:03

    To display the all details for each news post title ie. "news.id" which is the primary key, you need to use GROUP BY clause for "news.id"

    SELECT news.id, users.username, news.title, news.date,
           news.body, COUNT(comments.id)
    FROM news
    LEFT JOIN users
    ON news.user_id = users.id
    LEFT JOIN comments
    ON comments.news_id = news.id
    GROUP BY news.id
    
    0 讨论(0)
  • 2020-12-13 02:23

    You're missing a GROUP BY clause:

    SELECT news.id, users.username, news.title, news.date, news.body, COUNT(comments.id)
    FROM news
    LEFT JOIN users
    ON news.user_id = users.id
    LEFT JOIN comments
    ON comments.news_id = news.id
    GROUP BY news.id
    

    The left join is correct. If you used an INNER or RIGHT JOIN then you wouldn't get news items that didn't have comments.

    0 讨论(0)
提交回复
热议问题