我正在尝试使用我们为每个用户保留的登录历史记录来确定应用程序的保留用户。
我想知道在第1个月注册的用户,然后在第2个月回来,然后在第3个月又回来等等.....
单个查询很简单:
查询1
SELECT DISTINCT player_id
FROM login_history
WHERE timestamp BETWEEN UNIX_TIMESTAMP('2014-01-01 00:00:00')
AND (UNIX_TIMESTAMP('2014-02-01 00:00:00')-1);
上面给出了January
的唯一登录信息,简单。
查询2
SELECT DISTINCT player_id
FROM login_history
WHERE timestamp BETWEEN UNIX_TIMESTAMP('2014-02-01 00:00:00')
AND (UNIX_TIMESTAMP('2014-03-01 00:00:00')-1);
上面的内容现在为我提供了February
的唯一登录信息。
如何加入这两个或更多,给我所有结果的player_id共同点?
我尝试过使用IN语句但速度非常慢..
任何建议都将不胜感激
由于
答案 0 :(得分:4)
使用group by
和having
代替distinct
:
SELECT player_id
FROM login_history
GROUP BY player_id
HAVING SUM(timestamp BETWEEN UNIX_TIMESTAMP('2014-01-01 00:00:00') AND (UNIX_TIMESTAMP('2014-02-01 00:00:00')-1)) > 0 and
SUM(timestamp BETWEEN UNIX_TIMESTAMP('2014-02-01 00:00:00') AND (UNIX_TIMESTAMP('2014-03-01 00:00:00')-1)) > 0;
为了提高效率,您仍应包含where
:
SELECT player_id
FROM login_history
WHERE timestamp BETWEEN UNIX_TIMESTAMP('2014-01-01 00:00:00') AND (UNIX_TIMESTAMP('2014-03-01 00:00:00')-1)
GROUP BY player_id
HAVING SUM(timestamp BETWEEN UNIX_TIMESTAMP('2014-01-01 00:00:00') AND (UNIX_TIMESTAMP('2014-02-01 00:00:00')-1)) > 0 and
SUM(timestamp BETWEEN UNIX_TIMESTAMP('2014-02-01 00:00:00') AND (UNIX_TIMESTAMP('2014-03-01 00:00:00')-1)) > 0;
答案 1 :(得分:0)
也许这不是最好的答案,但是,你只需要提出另一个条件就可以了。
SELECT DISTINCT
player_id
FROM login_history
WHERE (timestamp BETWEEN UNIX_TIMESTAMP('2014-01-01 00:00:00')
AND (UNIX_TIMESTAMP('2014-02-01 00:00:00') - 1))
OR (timestamp BETWEEN UNIX_TIMESTAMP('2014-02-01 00:00:00')
AND (UNIX_TIMESTAMP('2014-03-01 00:00:00') - 1));
答案 2 :(得分:0)
另一种解决方案可能是使用别名
再次使用同一个表SELECT DISTINCT lh1.player_id
FROM login_history lh1 join login_history lh2 on lh1.player_id = lh2.player_id
WHERE lh1.timestamp BETWEEN UNIX_TIMESTAMP('2014-01-01 00:00:00')
AND (UNIX_TIMESTAMP('2014-02-01 00:00:00')-1)
AND lh2.timestamp BETWEEN UNIX_TIMESTAMP('2014-02-01 00:00:00')
AND (UNIX_TIMESTAMP('2014-03-01 00:00:00')-1);
如果行数太高,您可以使用子查询
SELECT DISTINCT lh1.player_id
FROM
(Select distinct player_id from login_history
WHERE lh1.timestamp BETWEEN UNIX_TIMESTAMP('2014-01-01 00:00:00')
AND (UNIX_TIMESTAMP('2014-02-01 00:00:00')-1) )lh1
JOIN
(Select distinct player_id from login_history
WHERE lh2.timestamp BETWEEN UNIX_TIMESTAMP('2014-02-01 00:00:00')
AND (UNIX_TIMESTAMP('2014-03-01 00:00:00')-1) )lh2 on lh1.player_id = lh2.player_id;
希望它有所帮助。 问候。