我有一个包含以下架构的表:
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
类型查询吗?
答案 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 = ?
或者,更简单的方法是将MAX
与CASE
:
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