如何使用Group By组合这两个MySQL查询

时间:2013-02-22 03:13:14

标签: php mysql sql database-design

我有这张表,用于通过 station_id 进行分组查询。

+------------------+---------------+------+-----+---------+-------+
| Field            | Type          | Null | Key | Default | Extra |
+------------------+---------------+------+-----+---------+-------+
| id               | varchar(50)   | NO   | PRI | NULL    |       |
| station_id       | tinyint(3)    | NO   |     | NULL    |       |
| game_type_id     | smallint(1)   | NO   | MUL | NULL    |       |
| price            | decimal(10,2) | YES  |     | 0.00    |       |
| date_created     | datetime      | YES  | MUL | NULL    |       |
| bet_no1          | tinyint(2)    | YES  |     | 0       |       |
| bet_no2          | tinyint(2)    | YES  |     | 0       |       |
+------------------+---------------+------+-----+---------+-------+

以下是我使用 GROUP BY station_id

在桌面上显示的查询
SELECT station_id,
COUNT(*) as bet_counts,
FORMAT(SUM(price),2) as gross
FROM bets 
WHERE bet_void=0 
AND date_created >= '2013-02-12 00:00:00' 
AND date_created < '2013-02-23 00:00:00' 
GROUP BY station_id

查询会给我。

+------------+------------+-------+
| station_id | bet_counts | gross |
+------------+------------+-------+
|          1 |         14 | 16.00 |
|          2 |          5 | 5.00  |
|          7 |         11 | 11.00 |
+------------+------------+-------+

但我还有另一个查询,它会计算每个 station_id 的每个特定投注( game_type_id )。我通常在循环语句中查询它。

SELECT COUNT(*) as count
FROM bets
WHERE game_type_id = 1
AND station_id = {station_id from first query}
AND date_created >= '2013-02-12 00:00:00'
AND date_created < '2013-02-23 00:00:00'

我的问题是,如何在一个查询中进行此操作并仍使用 GROUP BY station_id ,并获取每个 game_type_id 的投注数量?像这样的结果。

+------------+------------+-------+-------------------------+-------------------------+
| station_id | bet_counts | gross | count_of_game_type_id_1 | count_of_game_type_id_2 |
+------------+------------+-------+-------------------------+-------------------------+
|          1 |         14 | 16.00 |                      10 |                       4 |
|          2 |          5 | 5.00  |                       3 |                       2 |
|          7 |         11 | 11.00 |                      11 |                       0 |
+------------+------------+-------+-------------------------+-------------------------+

1 个答案:

答案 0 :(得分:1)

您可以通过将结果加在一起来完成此操作。但是,两个查询中的逻辑非常相似,因此您可以将它们组合成一个聚合查询:

SELECT station_id,sum(case when bet_void = 0 then 1 else 0 end) as bet_counts,
       FORMAT(SUM(case when bet_void = 0 then price else 0 end),2) as gross,
       sum(case when game_type_id = 1 then 1 else 0 end) as count
FROM bets b
where date_created >= '2013-02-12 00:00:00' AND date_created < '2013-02-23 00:00:00'
GROUP BY station_id