我有以下过滤器用于从数据库中获取值:
在提交表单时,我执行以下查询:
SELECT id, Month, Year, SUM(3R02) AS 3R02, SUM(3R05) AS 3R05
FROM varcosts
WHERE ( Month = 03
AND Month = 02
AND Year = 2013)
OR ( Month = 03
AND Month = 02
AND Year = 2014)
GROUP BY Year, Month
由于我使用servlet来执行查询,因此实现此查询变得很麻烦。就像一个问题,是否有更简单的方法来编写此查询?我正在寻找一种方法,我可以在其中包含用户选中的所有月份,而不是每个月重复AND Month = ..
。有一个简单的解决方案吗?
答案 0 :(得分:2)
您可以使用IN
声明执行此操作:
SELECT id, Month, Year, SUM(3R02) AS 3R02, SUM(3R05) AS 3R05
FROM varcosts
WHERE ( Month IN(03,02)
AND Year = 2013)
OR ( Month IN (02,03)
AND Year = 2014)
GROUP BY Year, Month
答案 1 :(得分:2)
您可以使用IN子句来避免重复OR语句:http://www.tutorialspoint.com/mysql/mysql-in-clause.htm
另外,你的查询不应该更像:
WHERE ((Month = 03 OR Month = 02) AND (Year = 2013)) OR ((Month = 03 OR Month = 02) AND Year = 2014)
甚至
WHERE (Month = 03 OR Month = 02) AND (Year = 2013 OR Year = 2014)
因为Month
不能同等于02
和03