mysql:使用相同的txn id对行进行分组

时间:2012-10-11 05:58:17

标签: mysql

我有两个表,一个事务表和transactions_items表:

交易:

ID Customer Amt
1  Bill     500
2  Helen    100

transactions_items:

ID Code Price
1  R2   100
1  R3   200
1  R5   100
2  R5   100

我想将它们分组:

ID Customer Code Price Amt
1  Bill     R2   100   500
            R3   200   
            R5   100
2  Helen    R5   100   100

这可能吗?

2 个答案:

答案 0 :(得分:0)

你可以做到这一点,但你需要做很多工作,在你的应用程序级别做,你将需要这个查询,

SELECT  a.*, 
        b.code,
        b.price,
        c.amt
FROM    transaction a
        INNER JOIN transaction_items b
            ON a.ID = b.ID
        INNER JOIN
        (
            SELECT ID, SUM(Price) Amt
            FROM transactions_Items
            GROUP BY ID
        ) c ON a.ID = c.ID
ORDER BY b.code

答案 1 :(得分:0)

你可以通过这个

select transactions.id,transactions.customer,transaction_items.code,transaction_items.price,transactions.amount 
from transactions  
left outer join 
transaction_items  on a.id=b.id;