使用内部联接从三个不同的表中选择内容

时间:2016-08-17 16:28:32

标签: mysql mysqli inner-join

好吧,我有三张桌子:

购物车:

ID | Product | Quantity
1    S1FG      3
1    C0K0      1
1    SLM1      6
2    S1FG      2
2    S94A      2

产品:

Code | Price
S1FG   10.00
C0K0   8.00
SLM1   19.50
S94A   2.00

用户:

ID | Nickname
1    Mark
2    Steve

我想要这个:

Nickname | Products | Total
Mark       10         155.00
Steve      4          24.00

简而言之,我想要一个用户列表,其中包含购物车中的商品,商品数量以及商品价格总和。

我试过了:

SELECT DISTINCT b.Nickname, SUM(a.Quantity) as Products, SUM(a.Quantity*c.Price) as Total 
FROM Cart a 
INNER JOIN Users b ON (a.ID = b.ID) 
INNER JOIN Products c ON (a.Product = c.Code)

但它没有用......

我该怎么办?

1 个答案:

答案 0 :(得分:1)

您需要GROUP BY昵称,否则您只需获得一行:

SELECT DISTINCT b.Nickname, SUM(a.Quantity) as Products, SUM(a.Quantity*c.Price) as Total 
FROM Cart a 
INNER JOIN Users b ON (a.ID = b.ID) 
INNER JOIN Products c ON (a.Product = c.Code)
GROUP BY b.Nickname