我有三個表order,ordered_dishes,ordered_dish_options。mysql一對多表加入
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鏈接到相應的菜。
一個觀察:order_id在ordered_dish_options中是多餘的 – Pete
不,因爲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
有它自己的方式 – Pete