MySQL View Problems
-
08-03-2021 - |
Question
I have the following tables, users which is self explanatory and answers which contains a list of responses on a given date for a specific 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
My aim is to build a view which would output the following:
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
I have been trying to do this in one SELECT statement but I don't believe it is possible, maybe I'm missing something? I can accomplish the output with multiple statements but I'm looking for a more elegant method which can sit in a view (or multiple views).
Thanks in advance!
Solution
This should work, but I recommend against using it unless the answers table will always be fairly small:
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
OTHER TIPS
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
try this
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
for nulls, I guess left outer join will work
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
This does the trick but instead of returning NULL for missing responses, it returns 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