如何为两个表

时间:2015-07-16 06:30:44

标签: mysql join

我有两个mysql表:

表-1:提前

id advance_id vamount
1 101 10000
2 101 20000
3 101 10000

表-2:购买

id advance_id item amount
1 101 Shirt 500
2 101 Pant 700
3 101 Pen 500
4 101 Shoe 1000

我想做什么,来自table-1的每个advance_id的vamount和来自table-2的相同advance_id的购买信息。在尝试通过以下查询时:

SELECT sum(a.vamount) as vamount, p.item, p.amount FROM advance as a INNER JOIN purchase as p ON a.advance_id=p.advance_id WHERE p.advance_id=101

我想以这种方式获取结果:

Total Advance Amount: 40000
item amount balance
shirt 500 39500
pant 700 38800
pen 500 38300
shoe 1000 37300

但它在结果集中返回一行。

如何正确地做到这一点?

2 个答案:

答案 0 :(得分:1)

尝试:

SELECT p.item, sum(a.vamount) as vamount, p.amount FROM advance as a INNER JOIN purchase as p ON a.advance_id=p.advance_id WHERE p.advance_id=101
group by p.item

答案 1 :(得分:0)

您的查询应该是这样的

SELECT sum(a.vamount) as vamount
    , p.item
    , p.amount 
FROM advance as a 
INNER JOIN purchase as p ON a.advance_id = p.advance_id
WHERE p.advance_id=101
GROUP BY p.item
    , p.amount

使用GROUP BY子句和可选项,您可以删除组{all}项的WHERE子句