MySQL / PHP:选择多个条件不起作用的位置

时间:2015-11-12 14:19:39

标签: php mysql sql

我有以下数据库条目:

id                date                start_time 
1                 2015-12-25          08:00:00
2                 2015-12-30          08:00:00
3                 2015-12-30          09:00:00             

现在我只想选择start_time条目08:00:0009:00:00都存在的条目的日期。

我尝试使用此SQL查询:

$sqlquery = mysqli_query($myconnection,"SELECT date 
                                        FROM mytable 
                                        WHERE start_time LIKE '08:00:00' 
                                        AND '09:00:00'") or die ("crashed");

但它会返回2015-12-252015-12-30两个日期。它应该只返回2015-12-30,因为此日期08:00:0009:00:00存在。

我想选择那些包含08:00:0009:00:00条目的日期。

不应选择只包含08:00:00条目但09:00:00没有条目的日期,也不应选择09:00:00条目但08:00:00没有条目的日期。< / p>

3 个答案:

答案 0 :(得分:2)

请勿将like用于日期/时间列。在这里,您似乎想要between

SELECT date
FROM mytable
WHERE start_time BETWEEN '08:00:00' AND '09:00:00';

您的原始配方解析如下:

WHERE (start_time LIKE '08:00:00') AND '09:00:00'

第二部分是布尔/整数上下文中的字符串值。它被转换为9,这总是正确的。因此,where子句最终等同于:

WHERE start_time = '08:00:00'

编辑:

您的澄清改变了我对该问题的理解。如果您希望两天都有,请使用聚合:

SELECT date 
FROM mytable 
WHERE start_time IN ('08:00:00', '09:00:00')
GROUP BY date
HAVING COUNT(*) = 2;

答案 1 :(得分:1)

我假设您基本上想要选择同时具有'08:00:00'和'09:00:00'的日期,那么您不应该使用'BETWEEN'。 试试这个查询:

SELECT t1.date
FROM mytable AS t1
INNER JOIN mytable AS t2 ON t1.date = t2.date
INNER JOIN mytable AS t3 ON t1.date = t3.date
INNER JOIN mytable AS t4 ON t1.date = t4.date
WHERE t1.start_time = '08:00:00' 
    AND t2.start_time = '09:00:00'
    AND t3.start_time = '10:00:00'
    AND t4.start_time = '11:00:00'
GROUP BY t1.date

或者您可以尝试其他方法

SELECT t1.date
FROM mytable AS t1
GROUP BY t1.date
HAVING SUM(IF(t1.start_time = '08:00:00', 1, 0)) > 0
AND SUM(IF(t1.start_time = '09:00:00', 1, 0)) > 0
AND SUM(IF(t1.start_time = '10:00:00', 1, 0)) > 0
AND SUM(IF(t1.start_time = '11:00:00', 1, 0)) > 0

答案 2 :(得分:0)

正如评论中所提到的,根据您实际想要对结果做什么,有不同的方法来实现它。

  1. Easy-&gt;只计算具有特定日期的记录

    select date, count(start_time) 
    from mytable 
    group by date 
    having count(start_time) > 1
    
  2. 2.Advanced-&gt;使用案例

    显示记录
       select * 
       from (
              Select date,
                    case when start_time = '08:00:00' then 1 end as startat8, 
                    case when start_time = '09:00:00' then 1 end as startat9 
               from mytable
             ) a 
        where a.startat8=1 and a.startat9=1;