4

如何定义具有两个计算字段的视图,例如...

 ('TableName'.'BlueSquares' + 'TableName'.'RedSquares') AS TotalSquares, ('TableName'.'BlueCirles' + 'TableName'.'RedCircles') AS TotalCircles

...并创建基于前两个计算字段的第三个计算字段,如...

 ('ViewName'.'TotalSquares' + 'ViewName'.'TotalCircles') AS TotalShapes

...?

当我按名称引用前两个计算字段时,我收到一条消息,指出这些字段是未知的。

谢谢!

4

3 回答 3

4

由于视图中不允许子查询,因此您需要通过创建多个视图来模拟它们。

例如,如果直接执行此查询将解决您的问题:

SELECT 
    TotalCircles + TotalSquares AS TotalShapes
FROM
    (SELECT 
        BlueCirles + RedCircles AS TotalCircles,
        BlueSquares + RedSquares AS TotalSquares
    FROM
        (SELECT
            2 AS BlueCirles,
            3 AS RedCircles,
            4 AS BlueSquares,
            5 AS RedSquares
        ) AS shapes
    ) as totals;

根据MySQL 文档,视图限制不能在 FROM 子句中包含子查询。要解决此限制并将此查询转换为视图,请将其分解为 3 个视图(每个子查询一个),最后一个给出所需的字段组合:

CREATE VIEW shapes AS
SELECT
    2 AS BlueCirles,
    3 AS RedCircles,
    4 AS BlueSquares,
    5 AS RedSquares;

CREATE VIEW totals AS
SELECT 
    BlueCirles + RedCircles AS TotalCircles,
    BlueSquares + RedSquares AS TotalSquares
FROM
    shapes;

CREATE VIEW result AS
SELECT 
    TotalCircles + TotalSquares AS TotalShapes
FROM
    totals;

SELECT * FROM result;
于 2009-12-13T04:20:09.767 回答
2

...创建基于前两个计算字段的第三个计算字段...

正如您所发现的,您不能在同一个 SELECT 中引用计算列。您的选择是:

复制逻辑

由于某些奇怪的原因,MySQL 不支持视图中的子查询:

CREATE OR REPLACE VIEW your_view AS
SELECT t.BlueSquares + t.RedSquares AS TotalSquares, 
       t.BlueCirles + t.RedCircles AS TotalCircles,
       t.BlueSquares + t.RedSquares + t.BlueCirles + t.RedCircles AS TotalShapes
  FROM TABLE t

分层视图

最不推荐的选项...

 CREATE OR REPLACE VIEW initial_view AS
    SELECT t.BlueSquares + t.RedSquares AS TotalSquares, 
           t.BlueCirles + t.RedCircles AS TotalCircles,
      FROM TABLE

 CREATE OR REPLACE VIEW layered_view AS
    SELECT iv.TotalSquares + iv.TotalCircles AS TotalShapes
      FROM initial_view iv
于 2009-12-13T04:31:04.743 回答
2

不幸的是,您尝试做的事情实际上不可能按照您的方式进行。通常,MySQL 视图可以看作是一个脚本化的 SELECT。视图的结果不会与其源分开存储在数据库中,而是在您引用该视图时进行计算。

大多数时候,当您从视图中选择时,MySQL 使用 MERGE 算法。这意味着它将您的视图的定义和引用它的视图的 SELECT 语句合并,以创建它实际运行的最终 SELECT。因此,您不能真正让 VIEW 引用自身。

您在此处的选择是 (1) 定义第二个视图,该视图引用第一个视图以创建您的总和,或者 (2) 像这样写出总和:

('TableName'.'BlueSquares' + 'TableName'.'RedSquares' + 'TableName'.'BlueCirles' + 'TableName'.'RedCircles') AS TotalShapes
于 2009-12-13T04:31:51.823 回答