如何在mysql的日期列中使用多个where条件时获取记录

时间:2018-11-29 09:28:39

标签: mysql

我有一个表(cookie_log),其中每个用户在不同的日期都有多个条目,因此我只需要使用 authenticate 来获取在所有日期中条目都是通用的那些用户,其中一栏的条件。

我有一个这样的表结构:-

表名 cookie_log

.......................................................
 cl_id   user_id    comment            datetime
.......................................................
   1     101       authenticate    2018-11-28 15:37:08
   2     102       loggedin        2018-11-28 15:37:08
   3     103       authenticate    2018-11-28 15:37:08
   4     101       authenticate    2018-11-29 15:37:08

在此记录中,我必须获得在两个 日期 2018-11-28 2018-11-29 。我想要此输出

   .................................
     cl_id   user_id    comment      
    ................................
       1     101       authenticate

我已经尝试过下面的查询,但是没有得到我想要的输出。

SELECT cookie_log.`cl_id`,cookie_log.`user_id` FROM `cookie_log`
where `comment`='login once authenticated' and (`datetime` like '%2018-11-28%') 
and (`datetime` like '%2018-11-29%') 

1 个答案:

答案 0 :(得分:0)

一种可能的方法是使用HAVING子句有条件地过滤掉:

SELECT user_id
FROM cookie_log
WHERE comment = 'authenticate' AND 
      DATE(datetime) IN ('2018-11-28', '2018-11-29')
GROUP BY user_id 
HAVING COUNT(DISTINCT DATE(datetime)) = 2  -- equal to number of dates to filter upon