MySQL视图问题

MySQL视图问题,mysql,sql,view,outer-join,cartesian,Mysql,Sql,View,Outer Join,Cartesian,我有以下表格,用户,这是不言自明的,答案,其中包含特定用户在给定日期的响应列表 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

我有以下表格,用户,这是不言自明的,答案,其中包含特定用户在给定日期的响应列表

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 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
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
对于空值,我想左外联接将起作用

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

这应该行得通,但我建议不要使用它,除非答案表总是相当小:

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

  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

谢谢,但是MySQL视图中不允许子查询。