我正在为我的网站撰写一个找到顶级海报的功能。我从成员表中选择记录,并按成员拥有的帖子数量进行排序。
我想在每位成员的最新帖子中显示相关信息。截至目前,我有一个正确的联接,找到每个成员发布的文章数量(不包括0个帖子的成员),这是查询的排序依据。还有一个左连接可以找到会员的头像信息,但这不相关。只是这样你才知道它是什么。
我从来都不擅长编写联接,尤其不是编写子查询。如何添加联接或子查询以查找每个成员的最新文章? 'articles'表中所需的列是article_id和title。
这是我现在的查询:
SELECT
m.member_id, m.display_name, m.avatar_id,
a.article_id, a.author_id, COUNT(a.article_id) AS total_articles,
av.attachment_id AS av_attachment_id, av.file_name
FROM members AS m
RIGHT JOIN articles AS a ON (m.member_id = a.author_id)
LEFT JOIN attachments AS av ON (m.avatar_id = av.attachment_id)
GROUP BY m.member_id
ORDER BY total_articles DESC
LIMIT 5
答案 0 :(得分:0)
这应该足够了:
SELECT
m.member_id,
m.display_name,
m.avatar_id,
a.article_id,
a.title,
(SELECT COUNT(*) FROM articles AS b WHERE b.author_id = m.member_id) AS total_articles,
av.attachment_id AS av_attachment_id,
av.file_name
FROM members AS m
JOIN articles AS a
ON a.article_id = (SELECT MAX(b.article_id) FROM articles AS b WHERE b.author_id = m.member_id)
LEFT JOIN attachments AS av
ON m.avatar_id = av.attachment_id
ORDER BY total_articles DESC
LIMIT 5