簡體   English   中英

MySQL 基於條件的連接表

[英]MySQL join table based on condition

我有一個要求,如果某些條件匹配,那么我需要應用 JOIN 否則,我不需要應用它。

例如

A、B 和 C 是表格

所以我需要加入 B 和 C 如果 B.id 不在(從 A 中選擇 entityId),否則將沒有加入。

同樣在這里 A 和 C 沒有共同的值。

Table A

    id entityId name
    1  xyz        abc
    2  bcd        z
    3  edc        x
    
    Table B
    id entityId shopRegID
    1  bcd       z
    
    Table C
    id entityId newEntityID ShopNewname
    1  xyz       xyze        abcd
    2  e          ee          sd

現在我有這樣的條件,我需要根據提供給我的 entityId 從這些表中獲取數據。 我需要刪除所有未注冊的商店(不在表 B 中)但包括重命名的商店(在表 C 中但不在 B 中)

假設如果給定 ('xyz','bcd','edc') output 應該包含 bcd (因為它在表 B 中) xyz (因為它在表 C 中)

這些表有非常大量的數據(10萬)

實現這一目標的最佳和高效方法是什么。

您可以按如下方式使用left joincoalesce

select * 
  from tableA A
  left join tableB B on a.entityid  = b.entityid
  left join tableB C on a.entityid  = c.entityid
 WHERE coalesce(b.entityid,c.entityid) is not null

聽起來您想要來自任a表中的實體。 這表明exists邏輯:

select a.*
from a
where exists (select 1 from b where b.entityId = a.entityId) or
      exists (select 1 from c where c.entityId = a.entityId)

暫無
暫無

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

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