簡體   English   中英

檢查表b中是否存在表主鍵

[英]Check if table a primary key is exist in table b

表A:ID,名稱等

表B:ID,表A-ID。

SELECT * FROM A;

並且我想在這種情況下以相同的結果返回一個布爾值(如果表B中存在A.ID)。

有幾種實現您所需要的方法。 以下是三種可能性。 這些都在執行計划以及數據庫實際如何執行它們方面有所不同,因此取決於您的記錄數,一個可能比另一個更有效。 最好自己看看。


1)使用LEFT JOIN並檢查B中的非空字段是否不為空,以確保記錄存在。 然后,如果關系為1:N,則應用DISTINCT子句,以僅顯示A中的行,而不重復。

select distinct a.*, b.id is not null as exists_b
from a
left join b on
  a.id = b.tablea-id

2)使用exists()函數,該函數將針對從表A返回的每一行進行評估。

select a.*, exists(select 1 from b where a.id = b.tablea-id) as exists_b
from a

3)使用子查詢表達式EXISTS的組合,並在兩個查詢中進行矛盾檢查表B中的記錄是否匹配。然后使用UNION ALL將兩個結果組合為一個。

select *, true as exists_b
from a
where exists (
  select 1
  from b
  where a.id = b.tablea-id
  )
union all
select *, false as exists_b
from a
where not exists (
  select 1
  from b
  where a.id = b.tablea-id
  )
select A.*, IFNULL((select 1 from B where B.TableA-ID = A.ID limit 1),0) as `exists` from A;

如果鍵存在,則以上語句將導致結果為1,如果鍵不存在,則結果為0。 如果B中有多個記錄,則限制1很重要

暫無
暫無

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

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