MySQL视图:在另一个计算字段中引用一个计算字段(按名称)

时间:2009-12-13 03:56:42

标签: sql mysql calculated-columns sql-view

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

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

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

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

...?

当我按名称引用前两个计算字段时,我收到一条消息,表明字段未知。

谢谢!

3 个答案:

答案 0 :(得分:2)

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

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

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 documentation视图,限制了无法在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;

答案 1 :(得分: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

答案 2 :(得分:2)

不幸的是,你正在尝试做的事情实际上不可能像你那样做。通常,MySQL视图可以被视为脚本SELECT。视图的结果不会与源文件分开存储在数据库中,而是在引用视图时进行计算。

大多数情况下,MySQL从视图中选择时使用MERGE算法。这意味着它合并了视图的定义和引用视图的SELECT语句,以创建它实际运行的最终SELECT。因此,你真的不能把VIEW引用给自己。

你在这里的选择是(1)定义第二个视图,它引用第一个视图来创建你的总和,或者(2)写出这样的总和如下:

('TableName'.'BlueSquares' + 'TableName'.'RedSquares' + 'TableName'.'BlueCirles' + 'TableName'.'RedCircles') AS TotalShapes