我有一个名为'checkins'的MySQL表,共有4列。
id | userIDFK | checkin_datetime | shopId
------------------------------------------------
1 | 1 | 2018-01-18 09:44:00 | 3
2 | 2 | 2018-01-18 10:32:00 | 3
3 | 3 | 2018-01-18 11:19:00 | 3
4 | 1 | 2018-01-18 17:57:00 | 3
5 | 1 | 2018-01-18 16:31:00 | 1
6 | 1 | 2018-01-19 08:31:00 | 3
基本上,我想查找用户在同一天和同一家商店多次签入(> = 2)的行。因此,例如,如果某个用户签入ID为1和4的行(同一用户,同一天,同一家商店),则查询应返回包含整行(ID,userIDFK,checkin_datetime,shopId)的匹配项。希望这有道理。
我已经尝试使用
SELECT id, userIDFK, checkin_datetime, shopId
FROM (
SELECT * FROM 'checkins' WHERE COUNT(userIDFK)>=2 AND COUNT(shopId)>=2
)
同一天,我不知道该怎么做,我知道这个查询已经走了,但这是我能做到的最好的。
有帮助吗?
感谢您的时间
答案 0 :(得分:1)
您可以尝试按userId checkin_date和shopID分组
SELECT userIDFK, checkin_datetime, shopId,COUNT(SHOPiD)
FROM checkins
GROUP BY userIDFK, DATE(checkin_datetime), shopId
HAVING COUNT(SHOPID)>1
编辑
您可以包括一个子查询来获取所有行:
select b.id,b.userIDFK, b.checkin_datetime, b.shopId
from checkins b
where (SELECT COUNT(SHOPiD)
FROM checkins a
where a.userIDFK=b.userIDFK and date(a.checkin_datetime)=date(b.checkin_datetime) and a.shopId=b.a.shopId
GROUP BY userIDFK, DATE(checkin_datetime), shopId)>1
答案 1 :(得分:1)
GROUPBY
可用于获取多次出现。
SELECT id, userIDFK, checkin_datetime, shopId
FROM checkins
GROUP BY userIDFK, DATE(checkin_datetime), shopId
HAVING count(id) > 1;
希望有帮助!
编辑:
使用内部联接可以实现它。这是查询:
SELECT c1.* FROM checkins c1 INNER JOIN checkins c2
ON c1.userIDFK = c2.userIDFK
AND date(c1.checkin_datetime) = date(c2.checkin_datetime)
AND c1.shopId = c2.shopId
AND c1.id != c2.id
干杯!