连接mySQL中的表以获取特定列

时间:2012-04-12 04:12:41

标签: php mysql

我有两张桌子:

- cart , cols are (painting_id, session_id, ip, user_agent)
- paintings , cols (painting_id, price)

现在我必须从表格购物车中选择绘画ID。我需要加入两张桌子,并从表格“绘画”中得到所有画作的价格总和。请注意,表格购物车没有价格列,必须从“绘画”表格中导入。只显示这些绘画的价格总和,并通过特定会话ID或电子邮件ID添加到购物车表中。

这是我到目前为止尝试的查询

SELECT p.SUM(price) FROM paintings 
p JOIN cart c ON p.painting_id = c.painting_id 
WHERE c.session_id = '$session'

2 个答案:

答案 0 :(得分:1)

应该是SUM(p.price)

答案 1 :(得分:0)

尝试此查询

SELECT cart.user_agent, sum(paintings.price)
from cart inner join
paintings on 
cart.painting_id=paintings.painting_id 
where session_id='$session'

如果您想要所有用户的总费用

SELECT cart.user_agent, sum(paintings.price)
from cart inner join
paintings on 
cart.painting_id=paintings.painting_id 
group by cart.session_id