[英]MySQL: Get data from multiple tables allowing nulls with a list of ids
I got this tables that look like this: 我得到的表看起来像这样:
table 1 表格1
|id|value1|value2|value3
table 2 表2
|id|value4|value5|value6
The id value in each table is unique but an id could appear in a table 1 but no in table 2. (value 1 is equal to value4 but if id dont appear in table 2 value4 would be null... ) 每个表中的id值都是唯一的,但是一个id可以出现在表1中,但不能出现在表2中。(值1等于value4,但如果id不出现在表2中,则value4将为null ...)
Then I got this a of ids and I want to get sometime like (supossing that id appear in table 1 but no in 2 and vice versa): 然后我得到了一个ID,我想得到一个类似的时间(假设该ID在表1中出现,但在表2中没有出现,反之亦然):
resultgrid resultgrid
| id | value1| value2| value3|value4|value5|value6
|838383|result1|result2|result3|null |null |null
|548438|null |null |null |result4|result5|result6
hope you guys can help me, thanks! 希望你们能帮助我,谢谢!
EDIT: query i've been trying (it's actually a set of collected pieces of answer i'd see in stack overflow) 编辑:查询我一直在尝试(实际上是我在堆栈溢出中看到的一组答案的集合)
SELECT t1.*, t2.value4, t2.value5, t2.value6
FROM table1 as t1
JOIN table2 AS t2 ON t2.id = t1.id
Where t1.id = t2.id = 838383
this get me 0 rows returned. 这给我0行返回。
I want to make it general to use the <2000 id list. 我想让它一般使用<2000 id列表。
Select
queries, using Left join
between the two tables. Left join
来使用两个不同的Select
查询。 In the first query, consider table1
as leftmost table; table1
视为最左边的表; and table2
as leftmost in the second query. table2
在第二个查询中最左边。 Where <right table id> IS NULL
to filter out rows where there is no matching entry in the rightmost table. Where <right table id> IS NULL
过滤掉最右边的表中没有匹配条目的行。 Union
to combine the resultset. Union
合并结果集。 Since there will not be any duplicates (due to our query results), we can use Union All
. Union All
。 Try the following: 请尝试以下操作:
SELECT t1.id, t1.value1, t1.value2, t1.value3,
t2.value4, t2.value5, t2.value6
FROM table1 AS t1
LEFT JOIN table2 AS t2 ON t2.id = t1.id
WHERE t2.id IS NULL
UNION ALL
SELECT t2.id, t1.value1, t1.value2, t1.value3,
t2.value4, t2.value5, t2.value6
FROM table2 AS t2
LEFT JOIN table1 AS t1 ON t1.id = t2.id
WHERE t1.id IS NULL
You want a full outer join
which MySQL does not support. 您需要MySQL不支持的
full outer join
。 In your case, you can emulate this with left join
: 在您的情况下,可以使用
left join
来模拟:
select t1.*, t2.value4, t2.value5, t2.value6
from (select 838383 as id
) i left join
table1 t1
on t1.id = i.id left join
table2 t2
on t2.id = i.id;
The list of ids you want to keep goes in the i
subquery. 您要保留的ID列表在
i
子查询中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.