2017-02-09 82 views
0

我有三個表order,ordered_dishes,ordered_dish_options。mysql一對多表加入

  • Orders表包含如客戶姓名,地址等
  • 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

    一個觀察:order_id在ordered_dish_options中是多餘的 – Pete

    +0

    不,因爲order_dish_id(odi)從order 1開始遞增的每個訂單的每一個訂單。因此order1具有3個dish和odi1,2,3。 order2有odi1,2,3,4的4道菜。所以當ordered_dish_options加入時,它必須加入order_id並鏈接到來自ordered_dish的相應odi – user4309314

    +0

    有它自己的方式 – Pete

    回答

    0

    我終於得到了與預期結果查詢:SELECT 訂單*,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)鄂爾多斯, GROUP_CONCAT(ordered_d ish_options.dish_option_id)的DOI 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個空間。