MySQL View with a SubQuery

主宰稳场 提交于 2019-12-11 07:26:45

问题


I have the following view that I need to port from Oracle to MySQL. This works perfectly in Oracle, but not in MySQL due to a subquery cannot exist in a view error. How can I convert this to make it work in MySQL? If I am to make another view for this, how would it impact performance? Is it advisable? If so, how can I do that? If a 2nd view is not that great of an idea, how to convert this? Thanks for your help!

CREATE OR REPLACE VIEW view_name (var1, var2, var3, var4, var5) AS 
SELECT SUM(A.var1a) var1,
        SUM(A.var2a) var2,
        SUM(A.var3a) var3,
        SUM(A.var4a) var4,
        SUM(A.var5a) var5
 FROM (SELECT CASE columnx when 'abc' then COUNT(E.ID) end var1a,
     CASE columnx when 'def' then COUNT(E.ID) end var2a,
     CASE columnx when 'ghi' then COUNT(E.ID) end var3a,
     CASE columnx when 'jkl' then COUNT(E.ID) end var4a,
                    COUNT(E.ID) var5a
             FROM   <list of tables>
            WHERE   <set of conditions>
         GROUP BY   columnx) A;

回答1:


You should be able to rewrite this using the following:

CREATE OR REPLACE VIEW view_name (var1, var2, var3, var4, var5) AS 
SELECT 
    sum(CASE columnx when 'abc' then 1 else 0 end) var1a,
    sum(CASE columnx when 'def' then 1 else 0 end) end var2a,
    sum(CASE columnx when 'ghi' then 1 else 0 end) end var3a,
    sum(CASE columnx when 'jkl' then 1 else 0 end)end var4a,
    COUNT(E.ID) var5a
FROM   <list of tables>
WHERE   <set of conditions>


来源:https://stackoverflow.com/questions/15232965/mysql-view-with-a-subquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!