将两个 table 合并为一个 table
Combine two tables into one table
我需要将用户 table 与所有用户图片一起排成一行,像这样
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 |
+------+--------+----------+----------+----------+
| ... | .... | .... | .... | .... |
+------+--------+----------+----------+----------+
这在 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;
我需要将用户 table 与所有用户图片一起排成一行,像这样
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 |
+------+--------+----------+----------+----------+
| ... | .... | .... | .... | .... |
+------+--------+----------+----------+----------+
这在 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;