所以我有多个表,我正在尝试创建一个视图来显示我在select语句中返回的所有内容。但是,似乎mysql不允许创建具有子查询的视图。
所以不确定如何将其转换为视图。
Select Title as "AlbumName" ,
Sum(trk1.Price * trk1.Quant) as "TotalSales"
From Album alb
INNER JOIN
(
SELECT AlbumId,
t1.UnitPrice as "Price" ,
t1.Quantity as "Quant"
FROM Track trk
INNER JOIN
(
SELECT TrackId, UnitPrice, Quantity
FROM InvoiceLine
WHERE InvoiceId IN ( SELECT InvoiceId FROM Invoice )
) AS t1 ON (trk.TrackId = t1.TrackId)
) as trk1 ON (alb.AlbumId = trk1.AlbumId)
Group By alb.AlbumId
答案 0 :(得分:5)
在VIEW
中创建MySQL
很简单,但有一些限制。 See HERE: MySQL View
其中一个限制是VIEW
s不能包含在FROM子句中包含子查询的SELECT
语句。因此,作为替代方案,首先为子查询创建一个包含IN
子句的视图。
CREATE VIEW InvoiceLineView
AS
SELECT DISTINCT a.*
FROM InvoiceLine a
INNER JOIN Invoice b
ON a.InvoiceId = b.InvoiceId;
创建视图后,您现在可以继续加入原始查询中的视图,以便现在可以创建完全正常的VIEW
。对于未计算的子查询,您不需要额外的视图。
CREATE VIEW AlbumSales
AS
Select Title as AlbumName,
Sum(t1.UnitPrice * t1.Quantity) as TotalSales
From Album alb
INNER JOIN Track trk
ON alb.AlbumId = trk1.AlbumId
INNER JOIN InvoiceLineView t1
ON trk.TrackId = t1.TrackId
Group By alb.AlbumId;
虽然,MySQL中的VIEWS
非常糟糕。
答案 1 :(得分:2)
如果你真的需要这个视图,你必须首先将子查询包装为视图。
CREATE VIEW vw_sub1 AS
SELECT TrackId, UnitPrice, Quantity
FROM InvoiceLine
WHERE InvoiceId
IN (SELECT InvoiceId FROM Invoice);
CREATE VIEW vw_sub2 AS
SELECT AlbumId, t1.UnitPrice Price, t1.Quantity Quant
FROM Track trk INNER JOIN
vw_sub1 t1 ON trk.TrackId = t1.TrackId;
CREATE VIEW vw_main AS
SELECT Title AlbumName, Sum(trk1.Price * trk1.Quant) TotalSales
FROM Album alb INNER JOIN
vw_sub2 trk1 ON alb.AlbumId = trk1.AlbumId
GROUP BY alb.AlbumId;
代码未经过测试
答案 2 :(得分:0)
不幸的是,MySQL在你的视图中不支持这样的子查询。我听说过的唯一解决方法是为每个子查询创建单独的视图,然后使用其他视图创建主视图。这有点奇怪,但确实如此。
在您的情况下,您需要创建3个视图 - 2个用于内部子查询,1个用于主要子视图。