[英]MySQL Join Multiple Rows as Columns
Say I have two tables in a MySQL Database. 假设我在MySQL数据库中有两个表。
Table 1: 表格1:
ID Name
1 Jim
2 Bob
Table 2: 表2:
ID Place Race_Number
1 2nd 1
1 3rd 2
1 4th 3
2 1st 1
2 2nd 2
2 2nd 3
When selecting rows from the database, is there any way to join rows from the second table as columns to the first table? 从数据库中选择行时,有没有办法将第二个表中的行作为列连接到第一个表? Currently I am using SELECT * FROM Table1 NATURAL JOIN Table2
. 目前我正在使用SELECT * FROM Table1 NATURAL JOIN Table2
。
This outputs: 这输出:
ID Name Place Race_Number
1 Jim 2nd 1
1 Jim 3rd 2
1 Jim 4th 3
2 Bob 1st 1
2 Bob 2nd 2
2 Bob 2nd 3
Currently I am sorting through this in my PHP script to sort it into an array. 目前,我正在我的PHP脚本中对其进行排序,以将其排序为数组。 This is a pain, as I have to look at the IDs and see if they're the same and then sort accordingly. 这是一个痛苦,因为我必须查看ID并查看它们是否相同然后进行相应排序。 I feel like there is a way to do this right in MySQL, without having to sort it into an array in the PHP. 我觉得有一种方法可以在MySQL中做到这一点,而无需将其排序到PHP中的数组中。 There can be an unlimited number of entries in the second table for each ID. 每个ID在第二个表中可以有无限数量的条目。
The desired result right from the MySQL query is: MySQL查询中的所需结果是:
ID Name Race1 Race2 Race3
1 Jim 2nd 3rd 4th
2 Bob 1st 2nd 2nd
I can't make columns for Race1, Race2 etc in the table themselves because there can be an unlimited number of races for each ID. 我不能在表格中为Race1,Race2等制作列,因为每个ID可以有无限数量的比赛。
Thanks for any help! 谢谢你的帮助!
An INNER JOIN
will suffice your needs. INNER JOIN
足以满足您的需求。 MySQL has no PIVOT
function by you can still simulate it using CASE
and MAX()
function. MySQL没有PIVOT
功能,你仍然可以使用CASE
和MAX()
函数来模拟它。
SELECT a.ID, a.NAME,
MAX(CASE WHEN b.Race_Number = 1 THEN b.Place ELSE NULL END) Race1,
MAX(CASE WHEN b.Race_Number = 2 THEN b.Place ELSE NULL END) Race2,
MAX(CASE WHEN b.Race_Number = 3 THEN b.Place ELSE NULL END) Race3
FROM Table1 a
INNER JOIN Table2 b
ON a.ID = b.ID
GROUP BY a.ID, a.Name
But if you have unknown number of RACE
, then a DYNAMIC SQL
is much more preferred. 但是如果你有未知数量的RACE
,那么DYNAMIC SQL
就更受欢迎了。
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT('MAX(CASE WHEN b.Race_Number = ', Race_Number,
' THEN b.Place END) AS ', CONCAT('`Race', Race_Number, '`'))
) INTO @sql
FROM Table2;
SET @sql = CONCAT('SELECT s.Student_name, ', @sql, '
FROM Table1 a
LEFT JOIN Table2 b
ON ON a.ID = b.ID
GROUP BY a.ID, a.Name');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.