加入两个MySQL查询

时间:2014-07-09 14:03:27

标签: php mysql

我正在尝试合并两个查询。

第一个给了我特定月份的所有注册。

SELECT player_id from player where registration_datetime like '%2013-12%';

第二个查询查找已在1月,2月和3月登录的用户

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 and
                               SUM(timestamp BETWEEN UNIX_TIMESTAMP('2014-03-01 00:00:00') AND (UNIX_TIMESTAMP('2014-04-01 00:00:00')-1)) > 0
                         ;

如何在不使用IN的情况下找到两个查询之间的常见player_id?

由于

3 个答案:

答案 0 :(得分:2)

您可以在2个查询UNION ALLgroup by player_id上使用having count(*) > 1

或使用内部联接(我会在联接查询中添加一个不同的颜色)

SELECT player_id
FROM login_history
join (SELECT distinct player_id from player where registration_datetime like '%2013-12%') s
  on s.player_id = player_id                   
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 and
       SUM(timestamp BETWEEN UNIX_TIMESTAMP('2014-03-01 00:00:00') AND (UNIX_TIMESTAMP('2014-04-01 00:00:00')-1)) > 0

答案 1 :(得分:1)

sqlfiddle会很好。

但您是否尝试加入这两个表然后对数据进行分组?

这样的事情:

SELECT p.player_id FROM player p 
JOIN login_history lh ON p.player_id = lh.player_id
WHERE p.registration_datetime like '%2013-12%'
GROUP BY p.player_id
HAVING SUM(lh.timestamp BETWEEN UNIX_TIMESTAMP('2014-01-01 00:00:00') AND (UNIX_TIMESTAMP('2014-02-01 00:00:00')-1)) > 0 and
       SUM(lh.timestamp BETWEEN UNIX_TIMESTAMP('2014-02-01 00:00:00') AND (UNIX_TIMESTAMP('2014-03-01 00:00:00')-1)) > 0 and
       SUM(lh.timestamp BETWEEN UNIX_TIMESTAMP('2014-03-01 00:00:00') AND (UNIX_TIMESTAMP('2014-04-01 00:00:00')-1)) > 0;

答案 2 :(得分:0)

您可以使用子查询和联接来完成此任务。查询的第一部分返回玩家的玩家ID。第二部分将您的login_history子集设置为您想要的ID,即用户在1月到3月之间登录的ID。此表与玩家联系,仅为您提供在Jan登记并在1月,2月和3月登录的用户的ID

SELECT a.player_id 
FROM player AS a 
INNER JOIN (
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 AND
SUM(timestamp BETWEEN UNIX_TIMESTAMP('2014-03-01 00:00:00') AND (UNIX_TIMESTAMP('2014-04-01 00:00:00')-1)) > 0) AS b
ON a.player_id = b.player_id
WHERE a.registration_datetime like '%2013-12%'