来自两个表的mySQL总和

时间:2019-01-12 16:25:58

标签: mysql sql

我正在尝试将由另一个表连接的两个表的PRICE相加。

tblcustomer   tblappointment   tblfinances
----------    --------------   -----------
CustomerID    AppointmentID    FinancesID
Name          CustomerID       CustomerID
              Price            Price

我正在尝试此代码,但出现错误#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;

2 个答案:

答案 0 :(得分:2)

您需要按以下步骤修复别名

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;

因为别名不能全部为数字表达式,除非用引号引起来

答案 1 :(得分:1)

我不建议使用以数字开头或以数字开头的别名。更重要的是,您需要认识到JOIN可能不匹配-这就是为什么您首先使用外部联接的原因。

所以:

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;