在mysql中加入和嵌套查询

时间:2015-08-02 18:47:55

标签: mysql sql

目前,我正在使用这个不错的查询:

select 
  users.name, 
  sum(race_results.winnings) as total_winnings, 
  count(CASE WHEN race_results.place=1 THEN 1 ELSE 0 END) AS times_won_first_place 
from users 
inner join race_results 
where race_results.userid = users.id and race_results.place = 1 
group by users.id 
order by total_winnings desc 

得到这个

 ************************************************
| name  | total_winnings | times_won_first_place |
| Bob   | 4000           | 4                     |
| John  | 1000           | 1                     |
 ************************************************

race_results表看起来像这样

*******************************************
| id | raceid | userid | place | winnings |
| 1  | 1      | 1      | 1     | 1000     |
| 2  | 1      | 2      | 5     | 50       |
| 3  | 1      | 3      | 6     | 50       |
| 4  | 2      | 1      | 1     | 1000     |
| 5  | 2      | 2      | 3     | 250      |
*******************************************

我想在这样的内容中包含四个以上的列

 ***************************************************************************
| name  | total_winnings | total_races | 1st_place | 2nd_place | 3rd_place |
| Bob   | 4000           | 5           | 4         | 0         | 0         |
| John  | 1000           | 5           | 1         | 1         | 1         |
 ***************************************************************************

如果我要对新列进行单独查询,请使用

 select count(raceid) from race_results where userid = 1
 select count(raceid) from race_results where userid = 1 and place = 1
 select count(raceid) from race_results where userid = 1 and place = 2
 select count(raceid) from race_results where userid = 1 and place = 3

进行单独的查询很容易,但是对于现有的查询,我必须使用CASE才能获得用户赢得第一名的次数。 (使用

count(CASE WHEN race_results.place=2 THEN 1 ELSE 0 END) 

返回相同的结果)。

我如何嵌套这些或将它们加入到我现有的查询中以获得我想要的内容?

1 个答案:

答案 0 :(得分:3)

你可以这样做:

select 
    users.name, 
    sum(race_results.winnings) as total_winnings, 
    count(*) AS total_races,
    sum(race_results.place = 1) AS times_won_first_place ,
    sum(race_results.place = 2) AS times_won_second_place,
    sum(race_results.place = 3) AS times_won_third_place 
from users 
inner join race_results 
where race_results.userid = users.id 
group by users.id 
order by total_winnings desc;

使用ANSI标准SQL,您可以在sum函数中使用case表达式,但由于MySQL(以及其他一些数据库)将布尔表达式评估为1,因此您可以将case表达式替换为仅评估的条件和然后把它们加起来。

因此,您可以CASE WHEN race_results.place=1 THEN 1 ELSE 0 END代替sum(race_results.place=1)并节省一些空间并输入:)

有关示例,请参阅此SQL Fiddle