繁体   English   中英

SQL查询多对多关系

[英]SQL query many-to-many realtionship

所以我有4张桌子:

车辆:

+----+-------------+------------------------+
| id |    title    |      description       |
+----+-------------+------------------------+
|  1 | Lorem ipsum | amet coscutor lorem et |
+----+-------------+------------------------+

prducers:

+----+-----------------+-----------------+----------+
| id |      name       |     website     | location |
+----+-----------------+-----------------+----------+
|  1 | Porsche Zentrum | www.example.com | {json}   |
+----+-----------------+-----------------+----------+

vehicle_images:

+------------+----------+
| 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 ,但是我认为这不是最好的解决方案。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM