MySQL:" AND"几行内的条件

时间:2016-04-29 13:05:54

标签: mysql group-by

表格如下:

id | event_id | date |

  1 | 2 | 2016-04-29
  2 | 2 | 2016-04-31
  3 | 1 | 2016-04-30
  4 | 1 | 2016-04-31

我需要运行一个查询,该查询将返回已分组的event_ids ,在请求的时间段内所有日期

例如,查看上表:

如果查询为(=> 2016-04-29 )( <= 2016-04-31 ),则不应返回任何事件。

如果查询为(=> 2016-04-30 )( <= 2016-04-31 ),则应返回event_id = 1。

如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

你想到这样的事情:

SELECT event_id AS eid FROM `test` WHERE date BETWEEN '2016-04-30' AND '2016-04-31'
GROUP BY event_id
HAVING COUNT(*) = (SELECT COUNT(*) FROM `test` WHERE event_id = eid)

或者这个:

SELECT event_id AS eid FROM `test` WHERE date IN ('2016-04-30', '2016-04-31')
GROUP BY event_id
HAVING COUNT(*) = (SELECT COUNT(*) FROM `test` WHERE event_id = eid)

BTW四月只有30天

答案 1 :(得分:0)

您应该通过以下查询获得解决方案

SELECT DISTINCT e1.event_id FROM Event_tbl e1 
    WHERE
(SELECT COUNT(DISTINCT(e2.event_id)) FROM Event_tbl e2 WHERE (e2.date BETWEEN '2016-04-30' AND'2016-04-31')) = 1 
    AND
e1.date BETWEEN '2016-04-30' AND'2016-04-31'