我有2张桌子 Maintable 和 Secondtable
在第二个表中是一列Maintable_ID和Price。
我在Workbench中建立了一个像这样的视图:
CREATE VIEW test AS
SELECT Maintable.ID as ID,
Maintable.Name as Name,
Maintable.Date as Date,
Secondtable.Price as Price,
From maintable
LEFT JOIN secondtable
ON Maintable.ID=Secondtable.Maintable_ID
我曾想过要做类似的事情:
SUM(Price) as GPrice FROM Secondtable WHERE Maintable.ID=Secondtable.Maintable_ID
我怎样才能找到Secondtable中所有项目的总价格,其中Secondtable.Maintable_ID = Maintable.ID
感谢您的帮助。
答案 0 :(得分:0)
试试这个..
CREATE VIEW test AS
SELECT Maintable.ID as ID,
Maintable.Name as Name,
Maintable.Date as Date,
sum (Secondtable.Price) as GPrice,
From maintable
LEFT JOIN secondtable
ON Maintable.ID=Secondtable.Maintable_ID
Group by
Maintable.ID as ID,
Maintable.Name as Name,
Maintable.Date as Date
答案 1 :(得分:0)
你走在正确的轨道上,你只是错过了一个group by
条款:
CREATE VIEW test AS
SELECT Maintable.ID as ID,
Maintable.Name as Name,
Maintable.Date as Date,
s.Sum_Price as Price,
FROM maintable m
LEFT JOIN (SELECT Maintable_ID, SUM(Price) AS Sum_Price)
FROM secondtable
GROUP BY Maintable_ID) s
ON m.ID=s.Maintable_ID
答案 2 :(得分:0)
您可以尝试以下查询
SELECT Secondtable.Maintable_ID ,
SUM(Secondtable.Price) as GPrice,
From Secondtable inner join Maintable ON Secondtable.Maintable_ID=Maintable.ID
GROUP BY Secondtable.Maintable_ID