我的博客页面中的SELECT查询存在一个问题。
当评论状态= 1时,我想要每个博客的评论数。
我申请以下查询..
SELECT CONCAT(u.first_name," ",u.last_name) name,r.*,IF(c.status=1,COUNT(c.id)) as comment
FROM users u RIGHT JOIN resources r ON u.id = r.created_by
LEFT JOIN comments c ON r.id = c.resource_id
WHERE r.type = 1
AND r.status=1
GROUP BY r.id
ORDER BY r.created_date DESC
LIMIT 0,5
但它给出了SYNTEX ERROR ..
Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ') as comment FROM users u RIGHT JOIN resources r ON u.id = r.created_by LEFT JOI' at line 1
请告诉我错在哪里。
由于
答案 0 :(得分:3)
if语句包含三个表达式。首先是表达式,第二个是条件为真时返回的值,第三个条件是假,因此你缺少第三个表达式。 请尝试以下代码
SELECT CONCAT(u.first_name," ",u.last_name) name,r.*,IF(c.status=1,COUNT(c.id), 0) as comment
FROM users u RIGHT JOIN resources r ON u.id = r.created_by
LEFT JOIN comments c ON r.id = c.resource_id
WHERE r.type = 1
AND r.status=1
GROUP BY r.id
ORDER BY r.created_date DESC
LIMIT 0,5
答案 1 :(得分:2)
Select concat(u.first_name," ",u.last_name) name,r.*,
case when c.status=1 then COUNT(c.id) end as comment
FROM users u RIGHT JOIN resources r ON u.id = r.created_by
LEFT JOIN comments c ON r.id = c.resource_id
WHERE r.type = 1
AND r.status=1
GROUP BY r.id
ORDER BY r.created_date DESC
LIMIT 0,5
答案 2 :(得分:0)
if
函数需要传递3个参数。 IF(expression ,expr_true, expr_false)
是应该如何使用的。
查看https://www.w3resource.com/mysql/control-flow-functions/if-function.php