我有一张表(t1):
id | from | to | item | price |
1 2014-03-14 00:00:00 2014-03-26 00:00:00 25 75
2 2014-03-27 00:00:00 NULL 25 50
3 2014-03-27 00:00:00 2014-04-01 00:00:00 26 80
4 2014-04-02 00:00:00 NULL 26 100
现在,如果是item = 25
,我想选择t1.id = 2
。在这种情况下,日期为2014-03-27
和NULL,因为不知道此价格何时结束。
如果是item = 26
,我希望在4月1日之前获得t1.id = 3
,从4月2日开始t1.id = 4
。
我该如何撰写查询?
修改
查询的想法:
SELECT `from`, IF(`to` IS NOT NULL, `to`, NOW()), price, item
FROM t1
WHERE NOW() BETWEEN `from`
AND IF(`to` IS NOT NULL,
`to`,
NOW()
)
ORDER BY item
今天(3月31日)的预期结果:
id | from | to | item | price |
2 2014-03-27 00:00:00 NULL 25 50
3 2014-03-27 00:00:00 2014-04-01 00:00:00 26 80
4月3日的预期结果:
id | from | to | item | price |
2 2014-03-27 00:00:00 NULL 25 50
4 2014-04-02 00:00:00 NULL 26 100
答案 0 :(得分:0)
您可以在select语句中包含列to
并避免使用if
表达式。
SELECT
id, `from`, `to`, price, item
FROM t1
WHERE NOW() BETWEEN
`from` AND IF(`to` IS NOT NULL, `to`, NOW() )
ORDER BY item;
对于任何未来的目标日期记录,
set @future_date := now() + interval 3 day;
SELECT
id, `from`, `to`, price, item, @future_date
FROM t1
WHERE @future_date BETWEEN `from`
AND IF(`to` IS NOT NULL, `to`, @future_date )
ORDER BY item;
演示 @ SQL Fiddle
答案 1 :(得分:0)
这就是它的工作原理
SELECT `from`, `to`, item, price
FROM t1
WHERE NOW() BETWEEN `from` AND `to`
OR `from` <= NOW() AND ISNULL(`to`)
ORDER BY item;
并证明它将来有效,这是4月3日的另一个问题
SELECT `from`, `to`, item, price
FROM t1
WHERE '2014-04-03' BETWEEN `from` AND `to`
OR `from` <= '2014-04-03' AND ISNULL(`to`)
ORDER BY item;
这是 SQL Fiddle
一切都很清楚?