如何将我的复杂mysql查询更改为mysql视图

时间:2012-10-27 09:29:06

标签: mysql sql view

我是mysql查询中的一个nubie,我想问一下,是否有人可以帮助我解决我的问题。我有这个复杂的(对我来说)sql。我想把它改成一个视图。

SELECT 
    username, 
    user_id,
    sum(result_points) AS count_points, 
    count(result_points) AS activity_done, 
    (
        (
            SELECT count(*) FROM `activity` WHERE periode_id = ''
        ) + 
        (
            SELECT
                IFNULL(sum(acs.result_points), 0) 
            FROM 
                user_activity ua 
            WHERE 
                periode_id = '' 
            AND ua.user_id = user_activity.user_id
            AND ua.result_points IS NOT NULL
        )
    ) AS total
    FROM 
        user_activity 
        LEFT JOIN users ON users.id = user_activity.user_id 
    WHERE 
        periode_id = '' 
    and user_id > 0 
    GROUP BY user_id 
    ORDER BY total DESC

有没有办法,取出“where”语句,以便我仍然可以将其更改为查看?

1 个答案:

答案 0 :(得分:0)

如果查询正确,请创建类似

的视图
Create View data as
SELECT 
    username, 
    user_id,
    sum(result_points) AS count_points, 
    count(result_points) AS activity_done, 
    (
        (
            SELECT count(*) FROM `activity` WHERE periode_id = ''
        ) + 
        (
            SELECT
                IFNULL(sum(acs.result_points), 0) 
            FROM 
                user_activity ua 
            WHERE 
                periode_id = '' 
            AND ua.user_id = user_activity.user_id
            AND ua.result_points IS NOT NULL
        )
    ) AS total
    FROM 
        user_activity 
        LEFT JOIN users ON users.id = user_activity.user_id 
    WHERE 
        periode_id = '' 
    and user_id > 0 
    GROUP BY user_id 
    ORDER BY total DESC

从视图中删除where子句并在视图中添加where子句,如

select * from data where user_id > 0