如何跨两行执行WHERE子句?

问题描述 投票:0回答:1

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_id 996应该被认为是打开的,因为store_period的第2行和第3行。

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

这是我的尝试:

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子句中的两个条件。

必须满足2个条件(现在开放,30分钟开放)。在这个例子中,它们满足2行,但它们可以被同一行满足两次。我该如何检查这些条件?

我想过用另一个联盟做这件事,但是即使只满足一个条件,它似乎会返回一行(例如,如果它现在打开,但在30分钟内没有打开)。

我想我需要以某种方式在两行中执行where子句,或者找到其他方法来执行它。

mysql sql
1个回答
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)
    )
© www.soinside.com 2019 - 2024. All rights reserved.