我正在尝试按评论数量排序的文章列表。我已经做了类似的过程来获得按照aticle的投票排序的列表,但我不知道为什么现在我不能让它工作。
SELECT a.*,cc.params as catparams,cc.title as cattitle,u.username,
CASE WHEN CHAR_LENGTH(a.alias) THEN CONCAT_WS(":", a.id, a.alias) ELSE a.id END as slug,
CASE WHEN CHAR_LENGTH(cc.alias) THEN CONCAT_WS(":", cc.id, cc.alias) ELSE cc.id END as catslug,
CASE WHEN (COUNT(rs.id)=0) THEN 0 ELSE COUNT(rs.id) END as total_comments
FROM jos_content AS a
INNER JOIN table_users AS u ON u.id = a.created_by
INNER JOIN table_categories AS cc ON cc.id = a.catid
LEFT JOIN table__comments AS rs ON rs.id = a.id
如果文章在评论表中至少有一个条目,则此代码仅返回结果;我想要的是获取所有文章的列表,如果注释表中没有条目,则返回零作为total_comments。我尝试过INNER JOIN,LEFT JOIN和RIGHT JOIN。
非常感谢任何帮助!
答案 0 :(得分:0)
我认为你需要一个子选择
SELECT
a.*,
cc.params as catparams,
cc.title as cattitle,
u.username,
CASE
WHEN CHAR_LENGTH(a.alias)
THEN CONCAT_WS(":", a.id, a.alias)
ELSE a.id END as slug,
CASE
WHEN CHAR_LENGTH(cc.alias)
THEN CONCAT_WS(":", cc.id, cc.alias)
ELSE cc.id END as catslug,
(SELECT COUNT(id) FROM table__comments WHERE id=a.id) as total_comments
FROM
jos_content AS a
INNER JOIN table_users AS u ON u.id = a.created_by
INNER JOIN table_categories AS cc ON cc.id = a.catid