[英]Joining two tables where some columns merge and others must be null
I feel like this question must have already been answered somewhere but my searching has not turned up anything relevant. 我觉得这个问题一定已经在某个地方回答了,但是我的搜索没有找到任何相关的内容。 If anyone is able to link to another answer I can accept this being marked as a duplicate and closed.
如果任何人都可以链接到另一个答案,我可以接受将其标记为重复并关闭。
I have three tables like this: 我有三个这样的表:
users(id)
things1(id, user_id, thing1_text)
things2(id, user_id, thing2_text)
For the purpose of this example, assume there's only one user in the users
table with an id
of 1
. 就本示例而言,假设在
users
表中只有一个用户,其id
为1
。
Let's say things1
looks like this: 假设
things1
看起来像这样:
id
1
2
user_id
2
user_id
1
1
thing1_text
1
thing1_text
im a thing 1
im a thing 1 too
And things2 looks like this: 而Things2看起来像这样:
id
1
2
user_id
2
user_id
1
1
thing2_text
1
thing2_text
im a thing 2
im a thing 2 too
I'm trying to create the query which will return this: 我正在尝试创建将返回此查询的查询:
user_id
1
1
1
1
thing1_text
1
thing1_text
im a thing 1
im a thing 1 too
NULL
NULL
thing2_text
NULL
thing2_text
NULL
NULL
im a thing 2
im a thing 2 too
My first, admittedly naive, attempt looked like this: 我的第一次尝试(虽然很幼稚)看起来像这样:
select users.id as user_id
, things1.thing1_text
, things2.thing2_text
from users
full outer join things1
on things1.user_id = users.id
full outer join things2
on things2.user_id = users.id;
However this doesn't put NULL
in any of the fields and instead combines them all - which I'm sure the more SQL minded among you probably figured when you read the query :D 但是,这不会在任何字段中放入
NULL
,而是将它们全部组合在一起-我敢肯定,当您阅读查询时,您可能会发现其中有更多的SQL思想:D
Anyway. 无论如何。 This is where I'm at.
这就是我的位置。 Any help at all would be greatly appreciated.
任何帮助将不胜感激。
You seem to want union all
. 您似乎想要
union all
。 Start with this: 从此开始:
select user_id, thing1_text, thing2_text
from ((select user_id, thing1_text, NULL as thing2_text
from things1 t1 join
users u
on t1.user_id = u.id
) union all
(select user_id, NULL, thing2_text
from things2 t2 join
users u
on t2.user_id = u.id
)
) tt
order by user_id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.