简体   繁体   English

MySQL嵌套选择查询?

[英]MySQL Nested Select Query?

Ok, so I have the following query: 好的,所以我有以下查询:

SELECT MIN(`date`), `player_name`
FROM `player_playtime`
GROUP BY `player_name`

I then need to use this result inside the following query: 然后我需要在以下查询中使用此结果:

SELECT DATE(`date`) , COUNT(DISTINCT  `player_name`)
FROM  `player_playtime /*Use previous query result here*/`
GROUP BY DATE( `date`) DESC LIMIT 60

How would I go about doing this? 我该怎么做呢?

You just need to write the first query as a subquery (derived table), inside parentheses, pick an alias for it ( t below) and alias the columns as well. 您只需要将第一个查询编写为子查询(派生表),在括号内,为它选择别名(下面的t )并为列添加别名。

The DISTINCT can also be safely removed as the internal GROUP BY makes it redundant: 由于内部GROUP BY使其冗余,因此也可以安全地删除DISTINCT

SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
FROM (
    SELECT MIN(`date`) AS `date`, `player_name`
    FROM `player_playtime`
    GROUP BY `player_name`
) AS t
GROUP BY DATE( `date`) DESC LIMIT 60 ;

Since the COUNT is now obvious that is only counting rows of the derived table, you can replace it with COUNT(*) and further simplify the query: 由于COUNT现在很明显只计算派生表的行数,因此可以用COUNT(*)替换它,并进一步简化查询:

SELECT t.date , COUNT(*) AS player_count
FROM (
    SELECT DATE(MIN(`date`)) AS date
    FROM player_playtime
    GROUP BY player_name
) AS t
GROUP BY t.date DESC LIMIT 60 ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM