所以我有 4 张 table :
车辆:
+----+-------------+------------------------+
| id | title | description |
+----+-------------+------------------------+
| 1 | Lorem ipsum | amet coscutor lorem et |
+----+-------------+------------------------+
生产者:
+----+-----------------+-----------------+----------+
| id | name | website | location |
+----+-----------------+-----------------+----------+
| 1 | Porsche Zentrum | www.example.com | {json} |
+----+-----------------+-----------------+----------+
车辆图像:
+------------+----------+
| vehicle_id | image_id |
+------------+----------+
| 1 | 1 |
+------------+----------+
图像:
+----+-------+-----+----------------------------------+
| id | title | alt | url |
+----+-------+-----+----------------------------------+
| 1 | Foo | Bar | https://example.com/imgs/img.jpg |
+----+-------+-----+----------------------------------+
vehicles
与 images
具有多对多关系。我需要的结果是所有车辆的列表、每辆车的生产商详细信息以及每辆车的所有图像。
我现在得到的只是所有车辆及其相应经销商的列表,但每辆车存在的次数与它有图像的次数一样:
+----+-------+---------------+---------+-----------+-----------+
| id | title | description | dealer | img_title | img_url |
+----+-------+---------------+---------+-----------+-----------+
| 1 | Car 1 | Description 1 | Porsche | img 1 | img-url-1 |
| 1 | Car 1 | Description 1 | Audi | img 2 | img-url-2 |
| 2 | Car 2 | Description 2 | Audi | img 3 | img-url-3 |
| 2 | Car 2 | Description 2 | VW | img 4 | img-url-4 |
+----+-------+---------------+---------+-----------+-----------+
最后是我的查询:
SELECT
v.id, v.title, v.description,
p.name AS dealer,
i.title AS img_title, i.url AS img_url
FROM vehicles v
LEFT JOIN producers p on p.id = v.producer_id
LEFT JOIN vehicle_images vi on vi.vehicle_id = v.id
LEFT JOIN images i ON vi.image_id = i.id;
由于以下错误消息,我无法使用 GROUP BY id
:
Error Code: 1055. Expression #9 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'projektarbeit.i.title' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
当然,我可以在 MySQL 设置中停用 only_full_group_by
,但我认为这不是最好的解决方案。
最佳答案
您可以使用子查询来获取必要的结果,例如:
SELECT vehicles.id,
vehicles.title,
vehicles.description,
producers.name AS dealer,
images.title AS img_title,
images.url AS img_url
FROM vehicles
LEFT JOIN images ON images.image_id =
(SELECT MAX(image_id)
FROM vehicle_images WHERE vehicle_id = vehicles.id)
LEFT JOIN producers ON producers.id = vehicles.producer_id
关于mysql - SQL查询多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52295407/