如何在两行中执行WHERE子句?

时间:2018-09-05 13:58:35

标签: mysql sql

  

store_i表

store_id, open_247
996, 0
  

store_period表

store_id, day, opentime, closetime
996, 3, 00:00:00, 04:00:00
996, 3, 08:00:00, 23:59:59
996, 4, 00:00:00, 04:00:00
996, 4, 08:00:00, 23:59:59

在PHP中,我确定当前时间,当前日期,从现在开始30分钟以及从现在开始30分钟的一天:

currenttime: 23:42:01
currentday: 3
timeplus30: 00:12:01
dayattimeplus30: 4

我正在尝试确定商店现在是否正在营业,并将在30分钟内营业。

对于上面的示例数据,由于store_period的第2行和第3行,应该将store_id 996视为已打开。

我想为所有具有open_247 = 1或具有适合当前时间和当前日期的行以及适合timeplus30和dayattimeplus30的行的商店检索store_id。

这是我的尝试:

SELECT store_i.store_id
FROM store_i 
WHERE store_i.open_247 = 1 
UNION 
SELECT store_i.store_id
FROM store_i 
JOIN store_period 
ON store_i.store_id = store_period.store_id 
WHERE ((CAST('23:42:01' AS TIME) >= opentime 
AND CAST('23:42:01' AS TIME) <= closetime 
AND store_period.day = 3) 
AND (CAST('00:12:01' AS TIME) >= opentime 
AND CAST('00:12:01' AS TIME) <= closetime 
AND store_period.day = 4))

对于上面的示例,它不返回任何结果,这是意外的。

我认为这是因为在第二个union子句的where子句中没有一行行同时满足这两个条件。

必须满足两个条件(立即打开,在30分钟内打开)。在此示例中,两行满足它们,但是同一行可能满足两次。如何检查这种情况?

我考虑过使用另一个联合来执行此操作,但是即使仅满足一个条件(例如,如果现在打开但在30分钟内不打开),它似乎也会返回一行。

我认为我需要以某种方式在两行之间执行where子句,或者找到其他方式来做到这一点。

1 个答案:

答案 0 :(得分:1)

我会尝试:

SELECT store_i.store_id
FROM store_i 
WHERE store_i.open_247 = 1 
    or (store_i.store_id in (
        SELECT store_i.store_id
        from store_period 
        where CAST('23:42:01' AS TIME) >= opentime 
        AND CAST('23:42:01' AS TIME) <= closetime 
        AND store_period.day = 3)
    and 
        (SELECT store_i.store_id
        from store_period 
        where CAST('00:12:01' AS TIME) >= opentime 
        AND CAST('00:12:01' AS TIME) <= closetime 
        AND store_period.day = 4)
    )
相关问题