具有多个in子句和count的Mysql

时间:2011-02-13 16:54:15

标签: mysql

我有以下sql查询:

SELECT field_number, COUNT(*) AS c FROM lead_detail WHERE field_number < 3 AND field_number > 2 AND lead_id IN (147,146,145,127,113) GROUP BY field_number

它返回:

field_number    c
2.1          5
2.2             5
2.3             1
2.4             1
2.5             5

我只想根据用户选择显示一些字段,所以我使用了:

SELECT field_number, COUNT(*) AS c FROM lead_detail WHERE field_number < 3 AND field_number > 2 AND lead_id IN (147,146,145,127,113,109,91,65,57,56,49) AND field_number IN (2.1,2.3) GROUP BY field_number

但现在使用此查询我得到0结果。我试图把AND field_number = 2.1没有成功。 任何线索为什么会发生这种情况或如何避免这种情况? lead_id id没有所有field_numbers,我想这可能就是原因。例如,在lead_id 147中我们可以找到field_numbers 2.1和2.3,在lead_id 146中我们找到2.4和2.5 感谢您的大力帮助

1 个答案:

答案 0 :(得分:1)

你的查询中有一个拼写错误,它假设是COUNT(*) AS c 你还有两个不必要的陈述使用field_number < 3 AND field_number > 2field_number IN (2.1,2.3) 所以最终查询应如下所示:

SELECT field_number, COUNT(*) AS c 
FROM lead_detail 
WHERE lead_id IN (147,146,145,127,113,109,91,65,57,56,49) 
   AND field_number IN (2.1,2.3)
GROUP BY field_number