使用子查询创建视图的正确语法?

时间:2015-04-10 01:14:12

标签: sql phpmyadmin create-view

我想使用以下代码创建视图:

SELECT t1.FirstName, t1.LastName, t2.Sum FROM Customer as t1,(SELECT CustomerID,Sum(Total) as Sum  FROM Invoice GROUP BY(CustomerID)) as t2 WHERE t1.CustomerID=t2.CustomerID 

对我有意义的方法是做

Create VIEW t2 as SELECT CustomerID,Sum(Total) as Sum  FROM Invoice GROUP BY(CustomerID)

Create VIEW CustomerInvoices as SELECT t1.FirstName, t1.LastName, t2.Sum FROM Customer as t1, t2  WHERE t1.CustomerID=t2.CustomerID  

但是这给了我一个语法错误,所以我不确定如何在主视图中调用第一个视图

1 个答案:

答案 0 :(得分:0)

正如您所注意到的,MySQL中不允许使用此语法(尽管在其他数据库中允许使用此语法):

SELECT t1.FirstName, t1.LastName, t2.Sum
FROM Customer as t1 JOIN
     (SELECT CustomerID,Sum(Total) as Sum  FROM Invoice GROUP BY(CustomerID)
     ) t2 
     ON t1.CustomerID = t2.CustomerID;

您可以将其改为:

SELECT c.FirstName, c.LastName, sum(total) as sum
FROM Customer c JOIN
     Invoice i
     ON c.CustomerID = i.CustomerId
GROUP BY c.FirstName, c.LastName;

这将在视图中有效。