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

lsmepo6l  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(346)

我有一个表(cookie\u log),其中有每个用户在不同日期的多个条目。因此,我必须只获取条目在所有日期中通用的用户,其中一列具有authenticate where条件。
我的table结构像that:-
表名cookie\u log

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

在此记录中,我必须获取那些在2018-11-28和2018-11-29日期都进行了身份验证的用户。我想要此输出

  1. .................................
  2. cl_id user_id comment
  3. ................................
  4. 1 101 authenticate

我尝试了下面的查询,但没有得到我想要的输出。

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

nhaq1z211#

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

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

相关问题