我有一个允许用户生成报告的PHP脚本,他们可以选择3个日期范围。 即。
2012-01-01 to 2012-01-31
AND
2011-01-01 to 2011-01-31
AND
2010-01-01 to 2010-01-31
但是当我进行查询,并且某个日期范围之间没有记录时,查询不返回任何值。
这是我的问题:
SELECT DealerName WHERE InterviewDate >= "2012/01/01 " AND InterviewDate <= " 2012/03/31"
AND InterviewDate >= "2012/07/01 " AND InterviewDate <= " 2012/09/31"
如果在1个日期范围内找到数据,我需要一个返回数据的查询,无论后续日期范围中是否没有数据。
数据汇总到一个表格中,相同的数据可能存在于多个日期。
例如:
dealerName 1 2012-01-01
dealerName 1 2012-02-31
dealerName 2 2012-03-01
dealerName 1 2012-06-01
dealerName 1 2012-06-31
所以如果我想查询2012-01-01和2012-02-31和2012-06-01和2012-06-31之间的数据。我意识到1个日期范围可能包含所有这些范围,但用户可能希望在这两个日期范围之间排除数据。
答案 0 :(得分:10)
访谈日期不能介于x和y之间,且仍介于z和zz之间。您错过了OR
- 另请参阅BETWEEN
运算符
SELECT DealerName
FROM table
WHERE InterviewDate BETWEEN '2012-01-01' AND '2012-01-31'
OR InterviewDate BETWEEN '2011-01-01' AND '2011-01-31'
OR InterviewDate BETWEEN '2010-01-01' AND '2010-01-31'
编辑,抱歉,错过了表名:)
答案 1 :(得分:4)
您需要使用OR
代替AND
WHERE (InterviewDate BETWEEN '2012-01-01' AND '2012-01-31')
OR
(InterviewDate BETWEEN '2011-01-01' AND '2011-01-31')
OR
(InterviewDate BETWEEN '2010-01-01' AND '2010-01-31')
更新1
我认为你有Relational Division
问题,
SELECT name
FROM table1
WHERE DATE BETWEEN '2012-01-01' AND '2012-02-31'
OR
DATE BETWEEN '2012-06-01' AND '2012-06-31'
GROUP BY name
HAVING COUNT(*) = 2
答案 2 :(得分:4)
为什么不使用OR代替AND?
SELECT DealerName WHERE ( InterviewDate >= "2012/01/01 " AND InterviewDate <= " 2012/03/31" ) OR ( InterviewDate >= "2012/07/01 " AND InterviewDate <= " 2012/09/31" )
答案 3 :(得分:3)
使用OR
代替AND
SELECT DealerName FROM tbl
WHERE InterviewDate >= '2012/01/01' AND InterviewDate <= '2012/03/31'
OR InterviewDate >= '2012/07/01' AND InterviewDate <= '2012/09/31'
答案 4 :(得分:1)
这是我带走的:)因为您正在检查month
2010年,2011年,2012年的year
。我们可以使用MONTH
和YEAR
个功能
SELECT DealerName
FROM yourtable
WHERE Month(InterviewDate) = 1
AND Year(InterviewDate) IN (2010, 2011, 2012)
;
SELECT DealerName
FROM yourtable
WHERE Month(InterviewDate) IN (1, 2) // if there are particular months
AND Year(InterviewDate) IN (2010, 2011, 2012)
;