2011-11-24 36 views
0

我有以下表格,用戶這是自我解釋和回答其中包含對特定用戶的特定日期的響應列表。MySQL視圖問題

users 
----- 
ID FIRST_NAME LAST_NAME 
1 Joe   Bloggs 
2 Fred   Sexy 
3 Jo   Fine 
4 Yo   Dude 
5 Hi   There 

answers 
------- 
ID CREATED_AT RESPONSE USER_ID 
1 2011-01-01 3   1 
2 2011-01-01 4   2 
3 2011-01-02 5   5 

我的目標是要建立一個視圖這將輸出如下:

USER_ID CREATED_AT RESPONSE 
1   2011-01-01 3 
2   2011-01-01 4 
3   2011-01-01 NULL 
4   2011-01-01 NULL 
5   2011-01-01 NULL 
1   2011-01-02 NULL 
2   2011-01-02 NULL 
3   2011-01-02 NULL 
4   2011-01-02 NULL 
5   2011-01-02 5 

我一直在努力做這一個SELECT語句,但我不相信這是可能的,也許我錯過了什麼?我可以用多個語句完成輸出,但我正在尋找一種更優雅的方法,可以坐在視圖(或多個視圖)中。

在此先感謝!

回答

2

這應該工作,但我建議不要使用它,除非答案表將永遠是相當小:

select u.id user_id, 
     a.created_at, 
     max(case when a.user_id = u.id then response end) response 
from users u 
cross join answers a 
group by u.id, a.created_at 
+0

完美!謝謝! – schone

0
select users.id as user_id, created_at, response from users 
    left outer join answers on users.id = answers.user_id 
    order by created_at, users.id 
0

試試這個

select t3.user_id, t3.created_at, a.response 
from 
(select t2.user_id as user_id, t1.created_at as created_at, null 
from 
(select distinct created_at 
from answers) t1, users t2) t3 answers a 
where t3.user_id = a.user_id and t3.created_at = a.created_at 

爲空值,我想LEFT OUTER JOIN將工作

select t3.user_id, t3.created_at, a.response 
from 
(select t2.user_id as user_id, t1.created_at as created_at, null 
from 
(select distinct created_at 
from answers) t1, users t2) t3 LEFT OUTER JOIN answers a 
ON t3.user_id = a.user_id and t3.created_at = a.created_at 
+0

感謝但子查詢不允許在MySQL視圖。 – schone

0

這樣做的竅門,但不是返回NULL爲缺少的響應,它返回0.

select 
    distinct u.id, a.created_at, MAX(IF(u.id=a.user_id, a.response, 0)) response 
    from users u, answers a 
    group by id, created_at 
    order by created_at, u.id