0

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

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

4 回答 4

1

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

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
于 2011-11-24T12:12:43.427 回答
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
于 2011-11-24T11:45:37.667 回答
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

对于空值,我猜左外连接会起作用

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
于 2011-11-24T11:53:56.637 回答
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
于 2011-11-24T12:44:53.110 回答