mySQL表上有多个连接

时间:2012-08-22 15:19:26

标签: mysql codeigniter join

我有2张桌子。第一个表包含大量用户数据。第二个表包含一个类列表,以及这些位置是否已填充。

我需要使用用户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       |
+-------------+-------------+------------+--------------+---+------------+

非常感谢任何帮助

1 个答案:

答案 0 :(得分:2)

您需要使用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)