希望這種格式更好......感謝OMG小馬,彼得·朗和他的耐心回答我的第一次嘗試。在複雜查詢中定義mysql中的視圖 - 嘗試#2
我正在設置一個遊戲,每個用戶每週選擇一個選手,有點像挑選你認爲會贏的球隊。我需要創建一個視圖,對於USER,CONTESTANT和WEEK的每個組合,該用戶在整個星期內累積選擇該特定CONTESTANT的次數。數據表是這樣的:
Data table "contestants"
contestant name
11 Aaron
12 Bob
13 Catherine
14 David
Data table "picks"
user week contestant
1001 1 11
1001 2 11
1002 1 12
1002 2 13
現在,我已經得到了工作,給我我想要的精確輸出代碼,但問題是,我不能讓一個觀點出來的,因爲有是子查詢。這裏是代碼和正確的輸出:
SELECT user, contestant ,week, count(valid_pick) num_picks
FROM
(
SELECT DISTINCT p.user , c.contestant, p.week
FROM contestants c , picks p
ORDER BY user , contestant , week
) t1
LEFT JOIN
(
SELECT user p_user , contestant p_contestant , week p_week ,
1 as valid_pick
FROM picks p
ORDER BY p.user , p_contestant , p_week
) t2
ON t1.user = t2.p_user AND t1.contestant = t2.p_contestant
AND t2.p_week <= t1.week
GROUP BY user , contestant , week
user contestant week num_picks
1001 11 1 1
1001 11 2 2
1001 12 1 0
1001 12 2 0
1001 13 1 0
1001 13 2 0
1001 14 1 0
1001 14 2 0
1002 11 1 0
1002 11 2 0
1002 12 1 1
1002 12 2 1
1002 13 1 0
1002 13 2 1
1002 14 1 0
1002 14 2 0
這有0是在正確的地方,並正確計算按周積累的選秀權。
但我真的需要這個視圖,所以我想創建子查詢作爲迷你視圖。下面是代碼:
CREATE OR REPLACE VIEW miniview1 AS
SELECT DISTINCT p.user , c.contestant, p.week
FROM contestants c , picks p
ORDER BY user , contestant , week
;
CREATE OR REPLACE VIEW miniview2 AS
SELECT user p_user , contestant p_contestant , week p_week ,
1 as valid_pick
FROM picks p
ORDER BY p.user , p_contestant , p_week
;
CREATE OR REPLACE VIEW myview AS
SELECT user, contestant ,week, count(valid_pick) num_picks
FROM miniview1 t1
LEFT JOIN miniview2 t2
ON t1.user = t2.p_user AND t1.contestant = t2.p_contestant
AND t2.p_week <= t1.week
GROUP BY user , contestant , week
但我得到 「MyView的」 是這樣的:
user contestant week num_picks
1001 14 1 1
1002 14 1 1
1001 14 2 1
1002 14 2 1
1002 11 1 1
1002 11 2 1
1001 12 1 1
1001 12 2 1
1001 13 1 1
1002 13 1 1
1001 13 2 1
1001 11 1 1
1001 11 2 2
1002 12 1 1
1002 12 2 1
1002 13 2 1
這顯然是錯誤的。這看起來像是一個簡單的替代品。我檢查了miniview1和miniview2,它們是完全正確的。有什麼想法發生在這裏?
謝謝,並感謝您對mysql(和stackoverflow)新手的耐心等待!
doxguy
謝謝。這是我試圖理解的迷你觀點的難題。 – doxguy 2010-01-09 05:49:34