gpt4 book ai didi

mysql - mySQL 表上的多个联接

转载 作者:行者123 更新时间:2023-11-29 08:47:59 25 4
gpt4 key购买 nike

我有两张 table 。第一个表包含大量用户数据。第二个表包含类(class)列表,以及职位是否已被填补。

我需要显示类以及用户 ID 和用户名。

我尝试过“连接” - 但名称似乎只是互相覆盖,所以每行只能得到一个名称。

用户表:

+----------+---------+
| user_ID | name |
+----------+---------+
| 1 | Smith |
+----------+---------+
| 2 | Jones |
+----------+---------+
| 3 | Tim |
+----------+---------+
etc

类别表:

+-------------+--------+--------+--------+---+---------+
| class_date | Spot 1 | Spot 2 | Spot 3 | . | Spot 16 |
+-------------+--------+--------+--------+---+---------+
| 2012/1/1 | 1 | 4 | 8 | . | 5 |
+-------------+--------+--------+--------+---+---------+
| 2012/2/1 | 2 | NULL | 1 | . | 3 |
+-------------+--------+--------+--------+---+---------+
| 2012/3/1 | 3 | 7 | NULL | . | NULL |
+-------------+--------+--------+--------+---+---------+

我想要实现的目标:

+-------------+-------------+------------+--------------+---+------------+
| class_date | Spot 1 | Spot 2 | Spot 3 | . | Spot 16 |
+-------------+-------------+------------+--------------+---+------------+
| 2012/1/1 | 1 - Smith | 4 - Ben | 8 - Drew | . | 5 - Loz |
+-------------+-------------+------------+--------------+---+------------+
| 2012/2/1 | 2 - Jones | NULL | 1 - Smith | . | 3 - Tim |
+-------------+-------------+------------+--------------+---+------------+
| 2012/3/1 | 3 - Tim | 7 - Dan | NULL | . | NULL |
+-------------+-------------+------------+--------------+---+------------+

任何帮助将不胜感激

最佳答案

为此,您需要使用LEFT JOIN。尝试一下,

SELECT  a.class_date,
CONCAT(a.Spot1, ' - ', b.name) AS `SPOT 1`,
CONCAT(a.Spot2, ' - ', c.name) AS `SPOT 2`,
CONCAT(a.Spot3, ' - ', d.name) AS `SPOT 3`,
... -- keep doing until last column (i guess up to 16)
FROM ClassTable a
LEFT JOIN `UserTable` b
ON a.Spot1 = b.user_ID
LEFT JOIN `UserTable` c
ON a.Spot2 = c.user_ID
LEFT JOIN `UserTable` d
ON a.Spot3 = d.user_ID
... ... -- keep doing until last column (i guess up to 16)

关于mysql - mySQL 表上的多个联接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12076345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com