Mysql

MySQL查詢:檢測另一個表中已刪除的行並顯示在結果表中

  • August 31, 2022

我在 MySQL 數據庫中有兩個表。

Table1
a_id
1
3
4
5
6


Table2
b_id
1
2
3

我想從 Table1 a_id 2 中找出缺失的行,並從 Table2 b_id 4、5、6 中找出缺失的行,這些行應該顯示在 deleted_from_a、deleted_from_b 列中,值為 1。

Expected output:
+----+----+--------------+--------------+
|a_id|b_id|deleted_from_a|deleted_from_b|
|   1|   1|             0|             0|
|    |   2|             1|             0|
|   3|   3|             0|             0|
|   4|    |             0|             1|
|   5|    |             0|             1|
|   6|    |             0|             1|
+----+----+--------------+--------------+

如何查詢輸出結果?

編輯1:

更新了表 1,與表 2 相比具有附加值。

編輯2:

更新了規範,一開始並不完美。

SELECT Table1.a_id,
      Table2.b_id,
      Table1.a_id IS NULL deleted_from_a,
      Table2.b_id IS NULL deleted_from_b
FROM ( SELECT a_id AS id FROM Table1
      UNION
      SELECT b_id FROM Table2 ) total
LEFT JOIN Table1 ON total.id = Table1.a_id
LEFT JOIN Table2 ON total.id = Table2.b_id
ORDER BY total.id

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=dc08079c1868673e586f946d1f662fa0


是否可以避免嵌套子查詢,只使用連接?– 克洛爾

SELECT t1.id a_id, t2.id b_id, 0 deleted_from_a, t2.id IS NULL deleted_from_b
FROM t1 
LEFT JOIN t2 ON t1.id = t2.id
UNION ALL
SELECT t1.id, t2.id, t1.id IS NULL, 0 
FROM t2 
LEFT JOIN t1 ON t1.id = t2.id
WHERE t1.id IS NULL
ORDER BY COALESCE(a_id, b_id)

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=6c9d5378dbc4821b8e559003c73b62f8

引用自:https://dba.stackexchange.com/questions/316267