问题
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