Sql 当有多个逗号分隔的外键时,如何连接左侧

Sql 当有多个逗号分隔的外键时,如何连接左侧,sql,left-join,Sql,Left Join,我有以下两个表格(订单和p设置): 我想把左边的订单表和psettings表连接起来。当product_id在订单表中只有一个时,它就起作用。我的问题是: SELECT `Order`.*, `products`.*, `psettings`.*, `City`.`name`, `Location`.`name` FROM `amrajegeachi`.`orders` AS `Order` LEFT JOIN `amrajegeachi`.`cities` AS `City` ON (`Or

我有以下两个表格(订单和p设置):

我想把左边的订单表和psettings表连接起来。当product_id在订单表中只有一个时,它就起作用。我的问题是:

SELECT `Order`.*, `products`.*, `psettings`.*, `City`.`name`, `Location`.`name` FROM `amrajegeachi`.`orders` AS `Order` LEFT JOIN `amrajegeachi`.`cities` AS `City` ON (`Order`.`city_id` = `City`.`id`) LEFT JOIN `amrajegeachi`.`locations` AS `Location` ON (`Order`.`location_id` = `Location`.`id`) LEFT JOIN `products` ON `Order`.`product_id` = `products`.`id` LEFT JOIN `psettings` ON `Order`.`product_id` = `psettings`.`product_id` WHERE `status` = 'No contact' 
如何在orders表中对多个逗号分隔的product_id执行相同的任务


注意:还有两个左连接关系表:“cities”和“locations”。

您不能这样做,因为您的数据库设计有缺陷。一个人应该避免在一个领域中存储多个东西:起初这似乎是一个明智的决定,但它不可避免地会让你的生活变得困难

设计此数据模型的正确方法是为
产品id
制作一个单独的表,如下所示:

create table order_product (
    order_id int not null
,   product_id int not null
)
此表在您的场景中如下所示:

order_id product_id
-------- ----------
       1          1
       2          1
       3          1
       4          1
       4          2
       4          3
现在,您可以使用
order\u product
制定联接,确保联接也适用于多产品订单:

SELECT `Order`.*, `products`.*, `psettings`.*, `City`.`name`, `Location`.`name`
FROM `amrajegeachi`.`orders` AS `Order`
LEFT JOIN `amrajegeachi`.`cities` AS `City` ON (`Order`.`city_id` = `City`.`id`)
LEFT JOIN `amrajegeachi`.`locations` AS `Location` ON (`Order`.`location_id` = `Location`.`id`)
-- This line takes care of dealing with multiple orders:
LEFT JOIN order_product ON `Order`.id=order_product.order_id
LEFT JOIN `products` ON order_product.product_id = `products`.`id`
LEFT JOIN `psettings` ON `Order`.`product_id` = `psettings`.`product_id` 
WHERE `status` = 'No contact'