2017-10-09 121 views
0

我的博客頁面中存在一個SELECT查詢問題。SELECT查詢IF條件

當評論狀態= 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: 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 

請告訴我,我錯了。

由於

+2

請出示你的語法錯誤,以便有人能幫助 – Pritamkumar

+2

你的if語句僅提供真實的部分即IF(條件,TRUE,FALSE)。更改爲IF(c.status = 1,COUNT(c.id),0) – jeff

+0

更新請檢查... – GYaN

回答

3

如果語句包含三個表達式。首先,表達式,其次是條件爲真時返回的值,如果條件爲假,則返回第三個,因此您缺少第三個表達式。 嘗試下面的代碼

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 
+0

謝謝....它的完成 – GYaN

1
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  

https://www.w3schools.com/sql/func_mysql_case.asp

+0

不,謝謝..它完成。 – GYaN

+0

這不提供問題的答案。一旦你有足夠的[聲譽](https://stackoverflow.com/help/whats-reputation),你將可以[對任何帖子發表評論](https://stackoverflow.com/help/privileges/comment);相反,[提供不需要提問者澄清的答案](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-c​​an- I-DO-代替)。 - [來自評論](/ review/low-quality-posts/17569963) –