2012-10-27 18 views
0

我在MySQL查詢一個nubie,我想問一下,是否如果有一個人誰可以幫我解決我的問題。我有這個複雜的(對我來說)sql。我想把它變成一個視圖。我該如何改變我的複雜的MySQL查詢到MySQL視圖

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」語句,以便我仍然可以將其更改爲查看?

+0

你得到任何錯誤,而定義這個視圖查詢? – Vikdor

回答

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子句中來看,像

select * from data where user_id > 0 
+0

感謝您的答案Vinit,並很抱歉,我發佈了ambigous的SQL。因爲問題是,我也希望periode_id也在where子句中。不僅是user_id。可能嗎? – ArdiAlam

+0

將periode_id添加爲列並將其作爲user_id以View的形式進行過濾 –