2017-03-05 62 views
0

order_master操纵两个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 

现在我想上面使用PHP和MySQL让我的网页上的第三个表的两个表结合起来。

为了

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

相关问题