MySQL Multiple Left Joins

前端 未结 2 1224
春和景丽
春和景丽 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: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.

提交回复
热议问题