我如何定义一个具有两个计算字段的视图,例如…
('TableName'.'BlueSquares' + 'TableName'.'RedSquares') AS TotalSquares, ('TableName'.'BlueCirles' + 'TableName'.'RedCircles') AS TotalCircles
…并根据前两个计算字段创建第三个计算字段,如…
('ViewName'.'TotalSquares' + 'ViewName'.'TotalCircles') AS TotalShapes
…?
当我按名称引用前两个计算字段时,我收到一条消息,指出字段未知。
谢谢!
由于视图中不允许子查询,因此您需要通过创建多个视图来模拟它们。
例如,如果直接执行此查询,将解决您的问题:
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;