将两个表合并为一个表

时间:2016-11-15 23:35:36

标签: mysql inner-join right-to-left

我需要将用户表与一行中的所有用户图像连接起来,就像这样

table user
+----+---------------+
|id  |   name        | 
+----+---------------+
| 1  | Mike          | 
| 2  | Jerry         |
| .. | .....         |  
+----+---------------+

table image
+------+---------+---------+
| id   | user_id |  img    |
+------+---------+---------+
|  1   |  1      | img_1   |
|  2   |  1      | img_2   |
|  3   |  1      | img_3   |
|  4   |  2      | img_4   |
|  ..  |  ....   | .....   |
+------+---------+---------+

我需要像这样生成SQL结果

+------+--------+----------+----------+----------+
| id   | name   |  img1    |  img2    |  img3    |
+------+--------+----------+----------+----------+
|  1   | Mike   |  img_1   |  img_2   |  img_3   |
+------+--------+----------+----------+----------+
|  ... | ....   |  ....    |  ....    |  ....    |
+------+--------+----------+----------+----------+

1 个答案:

答案 0 :(得分:2)

在mysql中本身不支持,但是你可以使用一个数据透视表来创建你的结果,但是如果可能的话我需要一些硬编码。

您的任务的简单解决方案可能是使用GROUP_CONCAT(),这将产生类似

的结果集
+------+--------+----------+----------+----------+
| id   | name   |  images                        |
+------+--------+----------+----------+----------+
|  1   | Mike   |  img_1;img_2;img_3             |
+------+--------+----------+----------+----------+
|  ... | ....   |                                |
+------+--------+----------+----------+----------+

如果这足够好,你可以用

实现
SELECT a.id, a.name, GROUP_CONCAT(b.img) images
FROM user a 
    INNER JOIN image b ON a.id = b.user_id
GROUP BY b.user_id;