MySQL View with a SubQuery

2019-07-31 16:31发布

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条回答
地球回转人心会变
2楼-- · 2019-07-31 17:28

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>
查看更多
登录 后发表回答