2016-11-05 138 views
2

我想有這樣的事情:Mysql如何在IF中使用IN in where子句?

SELECT 
    p.name_en AS 'province_$lang', 
    p.province_code AS 'province_code_$lang', 
    COUNT(u.id) AS 'total_$lang', 
    COUNT(u.id) AS total 
FROM applications AS a 
LEFT JOIN users AS u on u.id = a.user_id 
LEFT JOIN provinces AS p on p.province_code = u.province_code 
WHERE a.progress_status IN (0,1,2,3) AND IF(a.progress_status = 2,a.denial_type ,1) IN IF(a.`progress_status` = 2,(1,2,3),1) 
GROUP BY u.province_code 

假設我有在表中的兩個字段其中之一是progress_status能有這些0,1,2, or 3價值之一,而另一場denial_type,可以採取1,2, or 3,但只有denial_type可以把這些值之一,當progress_status爲2 所以我要檢查,如果progress_statusIN 0,1,2,3和這些記錄其progress_status爲2,則其denial_type應該IN 1,2,3

+0

它是一個'選擇query'。你也可以顯示你的整個查詢? –

+0

@MilanGupta我有更新我的問題。 – jones

回答

0

試試這個:

SELECT 
p.name_en AS 'province_$lang', 
p.province_code AS 'province_code_$lang', 
COUNT(u.id) AS 'total_$lang', 
COUNT(u.id) AS total 
FROM applications AS a 
LEFT JOIN users AS u on u.id = a.user_id 
LEFT JOIN provinces AS p on p.province_code = u.province_code 
WHERE a.progress_status IN (0,1,2,3) AND 
IF(a.progress_status = 2, 
(select denial_type from applications where denial_type IN (1,2,3)) ,1) 
GROUP BY u.province_code 

IF條件使用subquery只選擇那些denial_type,其值是IN (1,2,3)可能會解決你的問題。

希望它有幫助!

+0

子查詢返回多個行。 – jones

+0

嘗試使用'LIMIT':'從應用程序中選擇denial_type,其中denial_type IN(1,2,3)LIMIT 1' –

0

帖子彙總篩選應該做的伎倆

SELECT 
    p.name_en AS 'province_$lang', 
    p.province_code AS 'province_code_$lang', 
    COUNT(u.id) AS 'total_$lang', 
    COUNT(u.id) AS total 
FROM applications AS a 
LEFT JOIN users AS u on u.id = a.user_id 
LEFT JOIN provinces AS p on p.province_code = u.province_code 
GROUP BY u.province_code 
HAVING SUM(a.progress_status IN (0,1,2,3))>0 
AND SUM(a.progress_status = 2 AND a.denial_type IN(1,2,3))>0