如何获取某些用户执行event1但没有执行event2的行?

时间:2017-05-10 11:52:44

标签: mysql sql

在此查询中,我尝试查找访问该页面但未看到该内容的用户。我只能找到这个查询,但这个查询很慢。你有什么办法可以找到更好的解决方案吗?谢谢!

SELECT COUNT(*) FROM (
  SELECT u.id FROM users u INNER JOIN ( 
    SELECT pl.user_id FROM visited_logs vl 
    LEFT JOIN seen_logs sl ON sl.user_id = vl.user_id 
    WHERE vl.camp_id IN ('33') AND vl.camp_type = 0 
    AND sl.camp_id IS NULL 
  ) as joined ON joined.user_id = u.id 
  WHERE u.status = 'alive'
) derp

2 个答案:

答案 0 :(得分:1)

这是您的查询:

SELECT COUNT(*)
FROM (SELECT u.id
      FROM users u INNER JOIN
           (SELECT pl.user_id
            FROM visited_logs vl LEFT JOIN
                 seen_logs sl
                 ON sl.user_id = vl.user_id 
            WHERE vl.camp_id IN ('33') AND vl.camp_type = 0 AND
                  sl.camp_id IS NULL 
           ) joined
           ON joined.user_id = u.id 
      WHERE u.status = 'alive'
     ) derp;

我建议写这个:

select count(*)
from users u
where u.status = 'alive' and
      exists (select 1
              from visited_logs vl
              where vl.user_id = u.id and
                    vl.camp_id = 33 and
                    vl.camp_type = 0
             ) and
      not exists (select 1
                  from seen_logs sl
                  where sl.user_id = u.id  -- do you want camp_id here too?
                 );

我认为你错过了与sl.camp_id的比较。

对于此查询,您需要visited_logs(user_id, camp_type, camp_id)seen_logs(user_id, camp_id)上的索引。

答案 1 :(得分:1)

我不确定,但尝试这个解决方案,希望它有所帮助:

select count(*)
from users u 
join visited_logs vl on vl.user_id = u.id 
     and u.status = 'alive' 
     and vl.camp_id = 33 
     and vl.camp_type = 0 
join seen_logs sl on sl.user_id = vl.user_id
     and sl.camp_id is null