Skip to content
Advertisement

SELECT query IF CONDITION

I have one problem with my SELECT query in my blog page.

I want comment count of each blog when comment status=1.

I am apply following query..

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

but it giving SYNTAX 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

Please tell me where I am wrong.

Thanks

Advertisement

Answer

If statement contains three expressions. First, the expression, second the value returned if condition is true and third if condition is false so you are missing the third expression. Try the below code

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
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement