我有一个记录用户事件的数据库。 简化的表格如下所示
userid eventtype lastupdate
1 sent 5
1 opened 10
1 clicked 15
2 sent 5
3 sent 5
我正在尝试获取具有已发送事件类型的用户标识,但不是在一系列lastupdate之间获取打开的或单击的事件类型。
SELECT * FROM table WHERE (`eventtype` != "opened" AND (`lastupdate` BETWEEN 0 AND 10)) OR (`eventtype` != "clicked" AND (`lastupdate` BETWEEN 0 AND 10))
就我而言,但显然不会起作用,因为它会抓住用户ID 1,2和3.
虽然我希望它只抓住2和3。
实际的表格要复杂得多,因为它还必须使用连接和其他一些列,但如果我们能够弄清楚这部分,我可以完成其余的工作。
答案 0 :(得分:0)
如果你想找出user_ids并且我把你的问题字面化,那么这应该是你想要的:
SELECT user_id
FROM events
WHERE eventtype NOT IN ('opened', 'clicked')
AND lastupdate BETWEEN 0 AND 10
GROUP BY user_id;
这确实也会选择user_ids 2和3,因为他们也发送了匹配的事件......
答案 1 :(得分:0)
在没有任何存在条款的情况下尝试此操作,也许它符合您的需求
select *
from tst
where userid not in (
select userid from tst where eventtype in ('opened', 'clicked'))
and lastupdate between 0 and 10;
经过测试:sqlfiddle
答案 2 :(得分:0)
您可以使用NOT EXISTS
执行此操作:
SELECT *
FROM mytable AS t1
WHERE lastupdate BETWEEN 0 AND 10
AND eventtype = 'sent'
AND NOT EXISTS (SELECT 1
FROM mytable AS t2
WHERE t1.userid = t2.userid
AND t2.lastupdate BETWEEN 0 AND 10
AND t2.eventtype IN ('opened', 'clicked'))
以上将选择用户:
lastupdate
为BETWEEN 0 AND 10
和 eventtype = 'sent'
和 eventtype IN ('opened', 'clicked')
。