【问题标题】:How to join left while there are more than one foreign key of comma seperated如何在有多个逗号分隔的外键时左加入
【发布时间】:2015-06-27 11:27:34
【问题描述】:

我有以下两个表(订单和 psettings):

我想用 psettings 表加入 Orders 表。当 product_id 在 Order 表中只有一个时,它可以工作。我的查询是:

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' 

如何为订单表中的多个逗号分隔的 product_id 执行相同的任务?

注意:还有两个左连接关系表:“城市”和“位置”。

【问题讨论】:

    标签: sql left-join


    【解决方案1】:

    你做不到,因为你的数据库设计有缺陷。应该避免在一个字段中存储多个内容:起初这似乎是一个明智的决定,但它不可避免地会反过来让你的生活变得困难。

    设计此数据模型的正确方法是为product_ids 创建一个单独的表,如下所示:

    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_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' 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-29
      • 1970-01-01
      • 2015-12-03
      • 2011-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多