SQL查询多对多

时间:2018-09-12 12:39:02

标签: mysql join

所以我有4张桌子:

车辆:

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

vehiclesimages有多对多关系。结果,我需要的是所有车辆的清单,每个车辆的生产者详细信息以及每个车辆的所有图像。

我现在所得到的是所有车辆及其相应经销商的列表,但是每辆车的存在频率都与图像相同:

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

  

错误代码:1055。SELECT列表的表达式#9不在GROUP BY子句中,并且包含未聚合的列'projektarbeit.i.title',该列在功能上不依赖于GROUP BY子句中的列;这与sql_mode = only_full_group_by

不兼容

我当然可以在我的MySQL设置中停用only_full_group_by,但是我认为这不是最好的解决方案。

1 个答案:

答案 0 :(得分:0)

您可以使用子查询来获取必要的结果,例如:

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