订单主控
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
请帮忙。
最佳答案
您执行聚合来查找 sums 和 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,
关于php - 操作两个 MySQL 表并获取第三个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42608294/