Combine two tables into one table

帅比萌擦擦* 提交于 2019-12-25 09:28:47

问题


I need to join user table with all user images in one row, like this

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   |
|  ..  |  ....   | .....   |
+------+---------+---------+

I need to generate SQL results like this

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

回答1:


That's not natively supported in mysql, however you could use a pivot to create exactly your result, however that requires some hardcoding I'd avoid if possible.

A simple solution for your task could be using GROUP_CONCAT(), which would produce a resultset like

+------+--------+----------+----------+----------+
| id   | name   |  images                        |
+------+--------+----------+----------+----------+
|  1   | Mike   |  img_1;img_2;img_3             |
+------+--------+----------+----------+----------+
|  ... | ....   |                                |
+------+--------+----------+----------+----------+

If that's good enough, you can achieve that with

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;


来源:https://stackoverflow.com/questions/40621624/combine-two-tables-into-one-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!