簡體   English   中英

在條件為“ ON”的情況下聯接兩個表

[英]join two table with a condition in its “ON”

我有以下兩個表

表格1

|      id    |  category     |
|------------|---------------|
|      1     |  soap         |
|      2     |  grocery      |
|      3     |  snacks       |
|      4     |  vegetables   |
|      5     |  dairy        |
|      6     |  clothes      |
|      7     |  books        |
|      8     |  shoes        |  

表2

|      id    |  parent_cat   |      code     |
|------------|---------------|---------------|
|      1     |  soap         |      SHP      |
|      2     |  clothes      |      CLTH     |
|      3     |  snacks       |      SNCK     |
|      4     |  books        |      BOK      |
|      5     |  others       |      OTH      |

我想以這樣的方式加入他們:每個類別都將獲得一個代碼,如果其他表中不存在該類別,它將獲得與其他類別相對應的代碼

所需結果

|      id    |  category     |      code     |
|------------|---------------|---------------|
|      1     |  soap         |      SHP      |
|      2     |  grocery      |      OTH      |
|      3     |  snacks       |      SNCK     |
|      4     |  vegetables   |      OTH      |
|      5     |  dairy        |      OTH      |
|      6     |  clothes      |      CLTH     |
|      7     |  books        |      BOK      |
|      8     |  shoes        |      OTH      |

我想要第二張桌子的整行。 我不想使用子查詢或任何硬編碼,因為它是動態數據,因此“其他”一詞在不同情況下會有所不同。

當在Table2找不到記錄時,您希望在Table2上使用默認code值為'OTH'LEFT JOIN

SELECT
    t1.id,
    t1.category,
    COALESCE(t2.code, 'OTH') code,
    t2.id
FROM 
    Table1 t1
    LEFT JOIN Table2 t2 ON t1.category = t2.parent_cat

-創建第一個表並加載數據

create table #t1 (id int, category varchar(30) )

insert into #t1  (id,category)
values (1, 'soap')
insert into #t1  (id,category)
values (2, 'grocery')
insert into #t1  (id,category)
values (3, 'snacks')
insert into #t1  (id,category)
values (4, 'vegetables')
insert into #t1  (id,category)
values (5, 'dairy')
insert into #t1  (id,category)
values (6, 'clothes')
insert into #t1  (id,category)
values (7, 'books')
insert into #t1  (id,category)
values (8, 'shoes')

-創建第二張表並加載數據

create table #t2 (id int, parent_cat varchar(30) , code varchar(10))

insert into #t2 (id, parent_cat, code)
values(1,'soap','SHP')
insert into #t2 (id, parent_cat, code)
values(2,'clothes','CLTH')
insert into #t2 (id, parent_cat, code)
values(3,'snacks','SNCK')
insert into #t2 (id, parent_cat, code)
values(4,'books','SHP')
insert into #t2 (id, parent_cat, code)
values(5,'others','OTH')

-最終查詢

SELECT #t1.id, #t1.category, isnull(#t2.code, 'OTH') code  from #t1 
LEft join #t2 on #t1.category = #t2.parent_cat

-輸出

在此處輸入圖片說明

暫無
暫無

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

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