簡體   English   中英

如何從表中查找丟失的記錄-MySQL比較表

[英]How to find missing records from tables - MySQL compare tables

我在一個數據庫中有兩個MySQL表。 每個表都有一個公共字段。 這些表分別命名為tableatableb tafatableatbfatableb中包含相同的數據。 tableb從生成tablea ,使所有的行有沒有在tablea ,而在tableb ,有一些行。 我想顯示tafa領域,這是不存在的tableb 這些表可能看起來像這樣;

tablea

tafa | tafb   | tafc
-----------------------
1    | apple  | fruit
2    | carrot | veggie
3    | orange | fruit
4    | kiwi   | fruit

tableb

tbfa | tbfb   | tbfc
-----------------------
1    | apple  | fruit
2    | carrot | veggie
4    | kiwi   | fruit

我希望結果為;

3    | orange | fruit

如何使用PHP和MySQL執行此操作?

這句話應該給你想要的結果

select tablea.* from tablea  left join tableb on tbfa=tafa where tbfa is null

使用左聯接:

select a.*
from tablea as a left join tableb as b on a.tafa = b.tbfa
where b.tbfa is null

說明:

LEFT JOIN將返回右側表中的所有值,僅返回左側表中的匹配值。 沒有where的結果將是這樣的:

select a.*, b.tbfa from tablea as a left join tableb as b on a.tafa = b.tbfa

tafa | tafb   | tafc   | tbfa
-----------------------------
1    | apple  | fruit  |  1
2    | carrot | veggie |  2
3    | orange | fruit  |  NULL
4    | kiwi   | fruit  |  4

剩下的就是過濾掉tbfaNULL值的行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM