我有表,
-----------dates-------------
| id | date | user_id |
| 1 | 2016-01-01 | 1 |
| 2 | 2016-01-02 | 1 |
| 3 | 2016-01-03 | 1 |
| 4 | 2016-01-04 | 1 |
| 5 | 2016-01-01 | 2 |
| 6 | 2016-01-02 | 2 |
| 7 | 2016-01-03 | 2 |
| 8 | 2016-01-01 | 3 |
| 9 | 2016-01-02 | 3 |
我想进行查询以使user_id与所有日期匹配
等
SELECT user_id FROM dates WHERE xxxxxx IN ('2015-01-01', '2015-01-02', '2015-01-03', '2015-01-04')
#=> result: 1
SELECT user_id FROM dates WHERE xxxxxx IN ('2015-01-01', '2015-01-02', '2015-01-03')
#=> result: 1, 2
SELECT user_id FROM dates WHERE xxxxxx IN ('2015-01-01', '2015-01-02')
#=> result: 1, 2, 3
实际上,我的解决方案是使用group by with count,但日期可以重复。还有其他解决办法吗?
我使用postgresql
答案 0 :(得分:1)
您可以使用group by
和having
:
SELECT user_id
FROM dates
WHERE xxxxxx IN ('2015-01-01', '2015-01-02', '2015-01-03', '2015-01-04')
HAVING COUNT(DISTINCT xxxxxx) = 4;