MySQL查看问题

时间:2011-11-24 11:42:07

标签: 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_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语句中这样做,但我不相信这是可能的,也许我错过了什么?我可以使用多个语句完成输出,但我正在寻找一种更优雅的方法,它可以位于视图(或多个视图)中。

提前致谢!

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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

对于nulls,我猜左外连接将起作用

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

答案 3 :(得分: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