我有4个表,相关列总结如下:
customers:
id
name
credits:
id
customer_id # ie customers.id
amount
sales:
id
customer_id # ie customers.id
sales_items:
id
sale_id # ie sales.id
price
discount
我的想法是customers
列出了我们所有的客户,credits
列出了每次付款给我们的信息,sales
列出每次他们从我们这里购买的东西(但不是什么东西)他们购买了)sales_items
列出了他们在每次销售中购买的所有商品。因此,您可以看到credits
和sales
都与customers
有关,但sales_items
仅与sales
有关。
作为示例数据集,请考虑:
customers:
id | name
5 | Carter
credits:
id | customer_id | amount
1 | 5 | 100
sales:
id | customer_id
3 | 5
sales_items:
id | sale_id | price | discount
7 | 3 | 5 | 0
8 | 3 | 0 | 0
9 | 3 | 10 | 0
我在MySQL中试过这个:
SELECT c.*,
SUM( cr.amount ) AS paid,
SUM( i.price + i.discount ) AS bought
FROM customers AS c
LEFT JOIN sales AS s ON s.customer_id = c.id
LEFT JOIN sales_items AS i ON i.sale_id = s.id
LEFT JOIN credits AS cr ON cr.customer_id = c.id
WHERE c.id = 5
但它返回:
id | name | paid | bought
5 | Carter | 300 | 15
如果省略SUM()
函数,则返回:
id | name | paid | bought
5 | Carter | 100 | 5
5 | Carter | 100 | 0
5 | Carter | 100 | 15
因此,对于sales_items
中匹配的每条记录,它看起来都会返回一行,但每次都会在amount
列中填入credits
的相同值。我知道这种情况正在发生,但我不明白为什么会发生这种情况。
所以,有两个问题: 1。正在发生的事情是它通过所有行涂抹了一个值? 2。我可以在MySQL上使用什么SQL,以便我可以回复:
id | name | paid | bought
5 | Carter | 100 | 15
我知道我可以在子查询中将其全部拆分,但是只有连接才能实现它吗?当我解决这个问题时,我希望能够学习关于连接的一两件事。谢谢。
修改:我为此创建了一个SQL小提琴:http://sqlfiddle.com/#!2/0051b/1/0
答案 0 :(得分:0)
请试试这个
SELECT c.*,( SELECT SUM( cr.amount ) FROM customer c INNER JOIN credits cr ON
cr.customer_id = c.id WHERE c.id = 5 GROUP BY cr.id ) AS paid
,SUM( i.price + i.discount ) AS bought
FROM customers AS c INNER JOIN sales s ON s.customer_id = c.id
INNER JOIN sales_items i ON i.sale_id = s.id
INNER JOIN credits cr ON cr.customer_id = c.id
WHERE c.id = 5 GROUP BY s.id,cr.id
答案 1 :(得分:0)
select distinct (c.id, c.name), sum(i.price+i.discount) AS bought, cr.amount AS paid
from customer c, credits cr, sales s, sales_items i
where s.customer_id = c.id
and i.sale_id = s.id
and cr.customer_id = c.id and c.id = 5
group by c.id, c.name;
我不太确定,但试试这个。使用group by;这肯定是解决方案。