2017-03-05 9 views
0

order_masterは2つのMySQLのテーブルを操作し、第三のテーブル

order_id, name, address 
1, Andy, Hong Kong 
2, Sandy, NYT 

order_child

item_id, order_id, no_of_parcels, qty 
1, 1, 1, abc book, 3 
2, 1, 1, sss book, 5 
3, 2, 1, jj book, 2 
4, 2, 1, aa book, 3 

を取得する今、私は私のWebページ上の3番目のテーブルを取得するためにPHPとMySQLを使用して2つのテーブルの上に結合したいです。

ため

order_id, name, no_of_parcels, description, qty 
1, Andy, 2, (abc book, sss book), 8 
2, Sandy, 2, (jj book, aa book), 5 

助けてください。

+0

はあなたがどんなMySQLを試したことがありますか?これまでの投稿を投稿してください。 – Andrew

答えて

0

あなたは合計とgroup_concatsを見つけ、その後、マスターテーブルとそれに参加するために集計を行います。

select * 
from order_master m 
join (
    select order_id, 
     sum(num_of_parcels) num_of_parcels, 
     group_concat(description order by item_id separator ', ') description, 
     sum(qty) qty 
    from order_child 
    group by order_id 
    ) c 
    on m.order_id = c.order_id; 

あなたはサブクエリせずにこれをしたい場合:

select m.order_id, 
    m.name, 
    m.address, 
    sum(c.num_of_parcels) num_of_parcels, 
    group_concat(c.description order by c.item_id separator ', ') description, 
    sum(c.qty) qty 
from order_master m 
join order_child c 
    on m.order_id = c.order_id 
group by m.order_id, 
    m.name, 
    m.address, 
+0

Gurvありがとうございます。出来た。 – JayV

関連する問題