使用WHERE IN子句获得的结果少于预期

时间:2017-11-09 17:58:33

标签: mysql

我正在尝试此查询:

SELECT log_veh_id,
    MONTH( log_fecha_tiempo ) AS mes,
    YEAR(log_fecha_tiempo ) AS anio,
    SUM( log_total ) AS suma
    FROM  `dat_fuel_log`
        WHERE log_veh_id IN ('1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24')
GROUP BY MONTH( log_fecha_tiempo ) , YEAR( log_fecha_tiempo ) 
ORDER BY log_fecha_tiempo DESC

我只得到一些结果:

+------------+------+------+--------+
| log_veh_id | mes  | anio | suma   |
+------------+------+------+--------+
|          1 |    9 | 2017 |  85.00 |
|          1 |    8 | 2017 | 146.32 |
|          1 |    7 | 2017 | 187.26 |
|          1 |    6 | 2017 | 257.81 |
|          1 |    5 | 2017 | 263.65 |
|          1 |    4 | 2017 | 152.73 |
|          1 |    3 | 2017 | 193.28 |
|          1 |    2 | 2017 | 222.33 |
|          1 |    1 | 2017 | 114.02 |
+------------+------+------+--------+

还有更多的log_veh_id = 1和其他ID(log_veh_id)满足WHERE IN子句,而不仅仅是1。

考虑到所有log_veh_id值实际上都在值(WHERE IN)中,我希望返回所有表结果,就像删除WHERE IN子句一样。

2 个答案:

答案 0 :(得分:2)

如果log_veh_id是INT,则不应使用IN中的值引用

SELECT log_veh_id,
    MONTH( log_fecha_tiempo ) AS mes,
    YEAR(log_fecha_tiempo ) AS anio,
    SUM( log_total ) AS suma
    FROM  `dat_fuel_log`
        WHERE log_veh_id IN (1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24)
GROUP BY MONTH( log_fecha_tiempo ) , YEAR( log_fecha_tiempo ) 
ORDER BY log_fecha_tiempo DESC

否则如果是char,则应引用每个值

SELECT log_veh_id,
    MONTH( log_fecha_tiempo ) AS mes,
    YEAR(log_fecha_tiempo ) AS anio,
    SUM( log_total ) AS suma
    FROM  `dat_fuel_log`
        WHERE log_veh_id IN ('1','2','3','4','5','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24')
GROUP BY MONTH( log_fecha_tiempo ) , YEAR( log_fecha_tiempo ) 
ORDER BY log_fecha_tiempo DESC

答案 1 :(得分:0)

这个答案意味着补充其他答案/评论:

如果id都是顺序的,你也可以使用:

WHERE log_veh_id BETWEEN 1 AND 24

如果由于某种原因您无法将逗号分隔的列表转换为单个整数,则字符串的相应函数将为:

WHERE FIND_IN_SET(log_veh_id, '1,2,3,4,5,...') > 0