[英]mySQL sum totals from two tables
I am trying to sum the PRICE from two tables which are connected by another table. 我试图总结两个表之间的价格,这两个表由另一个表连接。
tblcustomer tblappointment tblfinances
---------- -------------- -----------
CustomerID AppointmentID FinancesID
Name CustomerID CustomerID
Price Price
I am trying this code but I am getting an error #1064 我正在尝试此代码,但出现错误#1064
SELECT c.CustomerID, (1.p1+2.p2) AS total_price FROM tblcustomer c
LEFT JOIN (SELECT CustomerID, SUM(Price) p1 FROM tblappointment GROUP BY CustomerID) 1 ON 1.CustomerID = c.CustomerID
LEFT JOIN (SELECT CustomerID, SUM(Price) p2 FROM tblfinances GROUP BY CustomerID) 2 ON 2.CustomerID = c.CustomerID;
You need to fix aliasing as follows 您需要按以下步骤修复别名
SELECT c.CustomerID, (t1.p1+t2.p2) AS total_price
FROM tblcustomer c
LEFT JOIN (SELECT CustomerID, SUM(Price) as p1
FROM tblappointment
GROUP BY CustomerID) t1 ON t1.CustomerID = c.CustomerID
LEFT JOIN (SELECT CustomerID, SUM(Price) as p2
FROM tblfinances
GROUP BY CustomerID) t2 ON t2.CustomerID = c.CustomerID;
since aliases can not be totally numeric expressions except they're quoted 因为别名除了引号外不能完全是数字表达式
I do not recommend using aliases that are or start with numbers. 我不建议使用以数字开头或以数字开头的别名。 More importantly, you need to recognize that the
JOIN
s may not match -- that would be why you are using outer joins in the first place. 更重要的是,您需要认识到
JOIN
可能不匹配-这就是为什么您首先使用外部联接的原因。
So: 所以:
SELECT c.CustomerID,
(COALESCE(a.price, 0) + COALESCE(f.price, 0)) AS total_price
FROM tblcustomer c LEFT JOIN
(SELECT CustomerID, SUM(Price) as price
FROM tblappointment
GROUP BY CustomerID
) a
ON a.CustomerID = c.CustomerID LEFT JOIN
(SELECT CustomerID, SUM(Price) as price
FROM tblfinances
GROUP BY CustomerID
) f
ON f.CustomerID = c.CustomerID;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.