用一个SELECT语句替换多个CREATE VIEW - MySQL

时间:2014-02-24 19:40:12

标签: mysql sql

我有以下sql脚本:

CREATE OR REPLACE ALGORITHM=UNDEFINED VIEW `day0` AS 
SELECT `c`.`customerId` AS `CustomerID`,SUM(`t`.`orderTotal`) AS `Day0`,
       `t`.`dateOfSale` AS `DateOfSale`,`c`.`initialDateOfSale` AS `InitialDateOfSale`     
FROM `customer` `c` LEFT JOIN
     `transaction` `t`
      on `t`.`customerId` = `c`.`customerId`
where `t`.`status` = 2 and `t`.`dateOfSale` <= DATE_ADD(`c`.`initialDateOfSale`, interval 1 day) 
GROUP BY `c`.`customerId';

CREATE OR REPLACE ALGORITHM=UNDEFINED VIEW `day30` AS 
SELECT `c`.`customerId` AS `CustomerID`,SUM(`t`.`orderTotal`) AS `Day30`,
       `t`.`dateOfSale` AS `DateOfSale`,`c`.`initialDateOfSale` AS `InitialDateOfSale` 
FROM `customer` `c` LEFT JOIN
     `transaction` `t`
     on `t`.`customerId` = `c`.`customerId`
where `t`.`status` = 2 and `t`.`dateOfSale` <= DATE_ADD(`c`.`initialDateOfSale`, interval 30 day) 
GROUP BY `c`.`customerId`;

CREATE OR REPLACE ALGORITHM=UNDEFINED VIEW `day60` AS 
SELECT `c`.`customerId` AS `CustomerID`,SUM(`t`.`orderTotal`) AS `Day60`,
       `t`.`dateOfSale` AS `DateOfSale`,`c`.`initialDateOfSale` AS `InitialDateOfSale`
FROM `customer` `c` LEFT JOIN
     `transaction` `t`
     on `t`.`customerId` = `c`.`customerId`
where `t`.`status` = 2 and `t`.`dateOfSale` <= DATE_ADD(`c`.`initialDateOfSale`, interval 60 day) 
GROUP BY `c`.`customerId`;

SELECT day0.customerid,day0.day0, day30.day30, day60.day60, 
FROM day0, day30, day60,
WHERE day0.customerid=day0.customerid and day0.customerid=day30.customerid and
      day0.customerid=day60.customerid

有没有用一个SELECT替换多个CREATE VIEW语句而不在数据库中创建新的视图/表?除此之外,最终用户将没有CREATE VIEW权限。

谢谢,

Oikif

2 个答案:

答案 0 :(得分:1)

您可以通过一个更简单的查询获得所需内容:

SELECT c.`customerId` AS `CustomerID` ,
       SUM(case when `t`.`dateOfSale` <= DATE_ADD(`c`.`initialDateOfSale`, interval 1 day)
                then `t`.`orderTotal`
                else 0
           end) AS `Day0`,
       SUM(case when `t`.`dateOfSale` <= DATE_ADD(`c`.`initialDateOfSale`, interval 60 day)
                then `t`.`orderTotal`
                else 0
           end) AS `Day60`,
       SUM(case when `t`.`dateOfSale` <= DATE_ADD(`c`.`initialDateOfSale`, interval 90 day)
                then `t`.`orderTotal`
                else 0
           end) AS `Day90`,
       `t`.`dateOfSale` AS `DateOfSale`, `c`.`initialDateOfSale` AS `InitialDateOfSale`
FROM `customer` `c` LEFT JOIN
     `transaction` `t`
     on `t`.`customerId` = `c`.`customerId`
where `t`.`status` = 2
GROUP BY `c`.`customerId`;

您可以围绕此查询创建视图。

答案 1 :(得分:0)

mySQL中的视图基本上只是一个表示查询的表。例如,如果您正在做这样简单的事情:

CREATE OR REPLACE VIEW 'myView' AS SELECT matNumber, SUM(inv) FROM inventory;
SELECT matNumber, totalInventory FROM myView;

您可以使用子查询替换它:

SELECT new_inventory.matNumber, 
       new_inventory.totalInventory 
FROM ( SELECT matNumber, sum(inv) FROM inventory ) new_inventory;

请记住每个派生表都需要别名。虽然这不是解决您确切问题的方法,但它应该为您提供总体方向。