SQL在特定日期和附加字段过滤器之间选择数据

时间:2019-02-23 07:49:38

标签: mysql sql

我有一个带有以下列的sql表payments

id|name|amount|reference_number|payment_date|status

这是一些值

1|John Doe|10.00|123456G|2019-02-21 08:00:21|confirmed
2|John Doe|10.00|FHFHgJJ|2019-02-21 10:05:50|pending
3|John Doe|10.00|57GHHFG|2019-02-22 12:10:32|pending
4|John Doe|10.00|GHTYNHJ|2019-02-22 09:52:26|confirmed
5|John Doe|10.00|123G456|2019-02-23 12:22:45|confirmed
6|John Doe|10.00|J123456|2019-02-23 13:00:21|pending

现在,我需要基于payment_datestatus提取数据,其中有时payment_date可以是一个范围或同一日期。

方案1:

SELECT * 
FROM payments 
WHERE payment_date >= '2019-02-21' AND payment_date <= '2019-02-21' AND status='confirmed' 
ORDER BY id DESC

应返回:

1|John Doe|10.00|123456G|2019-02-21 08:00:21|confirmed

场景2:

SELECT * 
FROM payments 
WHERE payment_date >= '2019-02-21' AND payment_date <= '2019-02-23' AND status='confirmed' 
ORDER BY id DESC

应返回:

1|John Doe|10.00|123456G|2019-02-21 08:00:21|confirmed
4|John Doe|10.00|GHTYNHJ|2019-02-22 09:52:26|confirmed
5|John Doe|10.00|123G456|2019-02-23 12:22:45|confirmed

有任何解决方法吗?

2 个答案:

答案 0 :(得分:2)

@strawberry建议使用时间以及日期来获取数据

SELECT * 
FROM payments 
WHERE payment_date >= '2019-02-21 00:00:00' AND payment_date <= '2019-02-21 
23:59:59' AND status='confirmed' 
ORDER BY id DESC

答案 1 :(得分:1)

您可以使用+ interval 1 day作为结束日期,并将<=更改为<,如下所示:

SET @startdate = '2019-02-21';
SET @enddate = '2019-02-21';

SELECT * 
FROM payments 
WHERE 
  payment_date >= @startdate 
  AND 
  payment_date < @enddate + interval 1 day
  AND 
  status='confirmed' 
ORDER BY id DESC;

请参见demo