我得到的表看起来像这样:
表1
|id|value1|value2|value3
表2
|id|value4|value5|value6
每个表中的id值都是唯一的,但是一个id可以出现在表1中,但不能出现在表2中。(值1等于value4,但是如果id不出现在表2中,则value4将为null ...)
然后我得到了一个ID,我想得到一个类似的时间(假设该ID在表1中出现,但在表2中没有出现,反之亦然):
结果网格
| id | value1| value2| value3|value4|value5|value6
|838383|result1|result2|result3|null |null |null
|548438|null |null |null |result4|result5|result6
希望你们能帮助我,谢谢!
编辑:我一直在尝试查询(实际上是我在堆栈溢出中看到的一组答案的答案)
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
这使我得到0行返回。
我想让人们普遍使用<2000 id列表。
答案 0 :(得分:0)
Select
来使用两个不同的Left join
查询。在第一个查询中,将table1
视为最左边的表;和table2
位于第二个查询的最左侧。Where <right table id> IS NULL
过滤掉最右边的表中没有匹配条目的行。Union
合并结果集。由于不会有任何重复项(由于我们的查询结果),因此我们可以使用Union All
。请尝试以下操作:
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
答案 1 :(得分:0)
您想要MySQL不支持的full outer 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;
您要保留的ID列表在i
子查询中。