mysql:从多个表中获取数据,允许使用id列表为null

xdyibdwo  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(496)

我有这样的table:
表1

  1. |id|value1|value2|value3

表2

  1. |id|value4|value5|value6

每个表中的id值都是唯一的,但是id可以出现在表1中,但在表2中没有(值1等于值4,但如果id未出现在表2中,则值4将为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

  1. 希望你们能帮我,谢谢!
  2. 编辑:我一直在尝试的查询(实际上是我在堆栈溢出中看到的一组收集的答案片段)

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

  1. 这将返回0行。
  2. 我想让它成为一般使用<2000 id列表。
fcipmucu

fcipmucu1#

你可以用两种不同的方法 Select 查询,使用 Left join 在两张table之间。在第一个查询中,考虑 table1 作为最左边的表;以及 table2 作为第二个查询中最左边的。
使用 Where <right table id> IS NULL 筛选出最右边表中没有匹配项的行。
使用 Union 合并结果集。由于不会有任何重复(由于我们的查询结果),我们可以使用 Union All .
请尝试以下操作:

  1. SELECT t1.id, t1.value1, t1.value2, t1.value3,
  2. t2.value4, t2.value5, t2.value6
  3. FROM table1 AS t1
  4. LEFT JOIN table2 AS t2 ON t2.id = t1.id
  5. WHERE t2.id IS NULL
  6. UNION ALL
  7. SELECT t2.id, t1.value1, t1.value2, t1.value3,
  8. t2.value4, t2.value5, t2.value6
  9. FROM table2 AS t2
  10. LEFT JOIN table1 AS t1 ON t1.id = t2.id
  11. WHERE t1.id IS NULL
展开查看全部
hs1rzwqc

hs1rzwqc2#

你想要一个 full outer join mysql不支持的。在你的例子中,你可以用 left join :

  1. select t1.*, t2.value4, t2.value5, t2.value6
  2. from (select 838383 as id
  3. ) i left join
  4. table1 t1
  5. on t1.id = i.id left join
  6. table2 t2
  7. on t2.id = i.id;

您要保留的ID列表将显示在 i 子查询。

相关问题