2

所以我有多个表,我正在尝试创建一个视图来显示我的 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
4

3 回答 3

6

创建一个VIEWinMySQL很简单,但有一些限制。请参阅此处:MySQL 视图

限制之一是VIEWs 不能有SELECT在 FROM 子句中包含子查询的语句。因此,作为替代方案,首先为包含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;

虽然,VIEWS在 MySQL 中是可怕的。

于 2013-03-18T02:20:16.360 回答
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;

代码未经测试

于 2013-03-18T02:19:10.980 回答
0

不幸的是,MySQL 不支持在您的视图中这样的子查询。我听说的唯一解决方法是为每个子查询创建单独的视图,然后使用其他视图创建主视图。这有点奇怪,但它确实有效。

在您的情况下,您需要创建 3 个视图 - 2 个用于内部子查询,1 个用于主查询。

于 2013-03-18T02:11:57.720 回答