将连接应用于整个mySQL表

时间:2012-07-20 04:50:09

标签: mysql join

我的数据库中有两个mySQL表

培训

+-------------+------------+------------+------------+-...-+------------+
| Training_ID | 09-06-2012 | 16-06-2012 | 23-06-2012 | ... | 28-12-2013 |
+-------------+------------+------------+------------+-...-+------------+
|     1       |    123     |    924     |   367      |     |   679      |
+-------------+------------+------------+------------+-...-+------------+
|     2       |    243     |    626     |   381      |     |   771      |
+-------------+------------+------------+------------+-...-+------------+
|     3       |    766     |    826     |   956      |     |   725      |
+-------------+------------+------------+------------+-...-+------------+

用户:

+---------+----------+
| User_ID | Name     |
+---------+----------+
|   123   | Fred     | 
+---------+----------+
|   924   | James    | 
+---------+----------+ 
|   367   | Tim      | 
+---------+----------+
|   766   | Mark     | 
+---------+----------+

我想要展示的是:

+-------------+------------+-------------+------------+-...-+------------+
| Training_ID | 09-06-2012 | 16-06-2012  | 23-06-2012 | ... | 28-12-2013 |
+-------------+------------+-------------+------------+-...-+------------+
|     1       | 123 - Fred | 924 - James | 367 - Tim  |     | 679 - Ben  |
+-------------+------------+-------------+------------+-...-+------------+
|     2       | 243 - Sarah| 626 - Smith | 381 - Exam |     | 771 - John |
+-------------+------------+-------------+------------+-...-+------------+
|     3       | 766 - Mark | 826 - Jone  | 956 - Case |     | 725 - Brett|
+-------------+------------+-------------+------------+-...-+------------+

注意:实际上有70列(所有格式与上面相同)。

我尝试使用连接 - 但我不能为每个列做一个。

有没有办法将连接应用于整个表?

1 个答案:

答案 0 :(得分:3)

这看起来像一个糟糕的设计,你为了产生你想要的格式而要执行的任何查询也看起来同样可怕,但这不可能:

你可以做的是对trainingusers表进行单一的笛卡尔连接,然后对GROUP BY进行training_id,然后进行一系列条件聚合将按training_id

将所有内容放在一行中
SELECT
    a.training_id,
    MAX(CASE WHEN a.`09-06-2012` = b.user_id THEN CONCAT(a.`09-06-2012`, ' - ', b.name) END) AS `09-06-2012`,
    MAX(CASE WHEN a.`16-06-2012` = b.user_id THEN CONCAT(a.`16-06-2012`, ' - ', b.name) END) AS `16-06-2012`,
    MAX(CASE WHEN a.`23-06-2012` = b.user_id THEN CONCAT(a.`23-06-2012`, ' - ', b.name) END) AS `23-06-2012`,
    MAX(CASE WHEN a.`28-12-2013` = b.user_id THEN CONCAT(a.`28-12-2013`, ' - ', b.name) END) AS `28-12-2013`
FROM training a
CROSS JOIN users b
GROUP BY a.training_id

您的MAX(CASE WHEN子句中需要尽可能多的SELECT ...列,因为您的表格中有列。

虽然这看起来也很丑陋,但它比为每列加入users表70不同时间效率要高得多。


SQLFiddle Demo只有四列