Mysql如何在where子句中使用IN和IF?

时间:2016-11-05 05:53:12

标签: mysql

我希望有这样的东西:

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为2时,progress_status只能获取其中一个值。 所以我想检查progress_statusIN 0,1,2,3,对于那些progress_status为2的记录,其denial_type应为{{1} } 1,2,3

2 个答案:

答案 0 :(得分: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   

subquery条件中使用IF仅选择值为denial_type的{​​{1}}可能会解决您的问题。

希望它有所帮助!

答案 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