MySQL进行自联接以将记录与公共ID组合在一起

时间:2014-05-25 23:52:50

标签: mysql sql activerecord

我有一个包含以下架构的表:

mysql> desc player_salaries;
+---------------+--------------+------+-----+---------+----------------+
| Field         | Type         | Null | Key | Default | Extra          |
+---------------+--------------+------+-----+---------+----------------+
| id            | int(11)      | NO   | PRI | NULL    | auto_increment |
| position      | varchar(10)  | NO   |     | NULL    |                |
| first_name    | varchar(100) | NO   |     | NULL    |                |
| last_name     | varchar(100) | NO   |     | NULL    |                |
| player_id     | int(11)      | NO   |     | NULL    |                |
| team          | varchar(255) | YES  |     | NULL    |                |
| opponent      | varchar(255) | YES  |     | NULL    |                |
| ppg           | int(11)      | YES  |     | NULL    |                |
| salary        | varchar(255) | NO   |     | NULL    |                |
| injury_status | varchar(255) | YES  |     | NULL    |                |
| site_id       | int(11)      | NO   | MUL | NULL    |                |
| created_at    | datetime     | YES  |     | NULL    |                |
| updated_at    | datetime     | YES  |     | NULL    |                |
| gamedate      | date         | NO   | MUL | NULL    |                |
| sport_id      | int(11)      | YES  |     | 0       |                |
+---------------+--------------+------+-----+---------+----------------+

这里奇怪的是,1个玩家每个gamedate有4行,每行属于不同的site_id。因此,要在特定日期为特定玩家获得每个site的工资,我可以编写如下查询:

SELECT salary,site_id from player_salaries where player_id = ? AND gamedate = ?

我想要的不是通过上述查询得到4行,而是每个玩家返回一行,每个site_id的工资都在自己的列中。这可以使用SELF JOIN类型查询吗?

1 个答案:

答案 0 :(得分:2)

一个选项是join表格回归自己,如标题所示。

SELECT ps1.salary, 
       ps2.salary, 
       ps3.salary, 
       ps4.salary
FROM player_salaries ps
    JOIN player_salaries ps1 ON 
         ps.player_id = ps1.player_id AND 
         ps.gamedate = ps1.gamedate AND
         ps1.site_id = 1
    JOIN player_salaries ps2 ON 
         ps.player_id = ps2.player_id AND 
         ps.gamedate = ps2.gamedate AND
         ps2.site_id = 2
    JOIN player_salaries ps3 ON 
         ps.player_id = ps3.player_id AND 
         ps.gamedate = ps3.gamedate AND
         ps3.site_id = 3
    JOIN player_salaries ps4 ON 
         ps.player_id = ps4.player_id AND 
         ps.gamedate = ps4.gamedate AND
         ps4.site_id = 4
WHERE ps.player_id = ? AND ps.gamedate = ?

或者,更简单的方法是将MAXCASE

一起使用
Select Max(Case When Site_id = 1 Then salary end) salary1,
    Max(Case When Site_id = 2 Then salary end) salary2,
    Max(Case When Site_id = 3 Then salary end) salary3,
    Max(Case When Site_id = 4 Then salary end) salary4
From player_salaries 
where ps.player_id = ? AND ps.gamedate = ?
Group by player_id