mysql一对二表加入

时间:2017-02-09 15:44:14

标签: mysql join one-to-many

我有三个表订单,ordered_dishes,ordered_dish_options。

  • 订单表包含客户名称,地址等订单信息。
  • ordered_dishes表包含order_id和dish_id以及每个订单唯一的 ordered_dish_id。 ordered_dish_id是因为可以有相同的菜+ dish_options的不同组合。和金额是订购的相同组合的数量
  • ordered_dish_options包含order_id,ordered_dish_id(fk到ordered_dishes.ordered_dish_id),dish_option_id
  • orders
    ------
    order_id | customer_name
    1        | John smith
    
    ordered_dishes
    --------------
    order_id | ordered_dish_id | dish_id | amount
    1        | 1               | 3       | 1
    1        | 2               | 3       | 2
    1        | 3               | 6       | 1
    
    ordered_dish_options
    --------------------
    order_id | ordered_dish_id | dish_option_id
    1        | 1               | 2
    1        | 2               | 4
    1        | 3               | 3
    

    注意:在这个例子中有两个dish_id = 3的菜,但菜+ dish_option组合不同。

    我有以下查询:

    "SELECT orders.*,
    GROUP_CONCAT(ordered_dishes.dish_id SEPARATOR ', ') dish_ids,
    GROUP_CONCAT(ordered_dishes.amount SEPARATOR ', ') dish_amounts,
    GROUP_CONCAT(ordered_dishes.ordered_dish_id SEPARATOR ', ') dish_odi,
    GROUP_CONCAT(ordered_dish_options.ordered_dish_id SEPARATOR ', ') do_odi,
    GROUP_CONCAT(ordered_dish_options.dish_option_id SEPARATOR ', ') dish_option_ids
    FROM orders
    LEFT JOIN ordered_dishes ON orders.order_id=ordered_dishes.order_id 
    LEFT JOIN ordered_dish_options ON orders.order_id=ordered_dish_options.order_id 
    WHERE orders.order_id=1"
    

    这个查询给了我这个:

    order_id, 
    orderdata, 
    dish_ids='3,3,6,3,3,6,3,3,6', 
    dish_amounts='1,2,1,1,2,1,1,2,1', 
    dish_odi='1,2,3,1,2,3,1,2,3', 
    do_odi='1,1,1,1,1,1,1,1,1' 
    dish_option_id='2'
    

    我想要的是所有order_data,dish_id +金额+ ordered_dish_id,dish_option_id + ordered_dish_id。我希望最后两个表中的ordered_dish_ids将dish_option链接到相应的菜。

    1 个答案:

    答案 0 :(得分:0)

    我终于得到了一个预期结果的查询:         SELECT orders。*,ordered_dishes.dishids,ordered_dishes.amounts,ordered_dish_options.odos,ordered_dish_options.dois         来自订单         LEFT JOIN(SELECT order_id,             GROUP_CONCAT(ordered_dishes.dish_id)dishids,             GROUP_CONCAT(ordered_dishes.amount)金额             来自ordered_dishes             GROUP BY order_id)             ordered_dishes ON orders.order_id = ordered_dishes.order_id         LEFT JOIN(SELECT order_id,             GROUP_CONCAT(ordered_dish_options.ordered_dish_id)odos,             GROUP_CONCAT(ordered_dish_options.dish_option_id)dois             FROM ordered_dish_options             GROUP BY order_id)             ordered_dish_options ON orders.order_id = ordered_dish_options.order_id         WHERE orders.order_id = 6

    所以编辑器有点蹩脚,我无法通过4个空格查询代码格式。