6 兩表兩列資料匹配

2021-10-19 06:56:03 字數 2790 閱讀 1248

**問題:**資料庫2張表做關聯,a表字段a,b表字段b,如果a列包含b列的內容,就關聯,這個應該怎麼寫?mysql資料庫

資料表示例如下:

一、

with cte1 as (

select 1 as fa,

'a' as fb,

'c' as fc

union all

select 2 as fa,

'b' as fb,

'd' as fc

union all

select 3 as fa,

'c' as fb,

'x' as fc

), cte2 as (

select 1 as fa,

'c' as fb

union all

select 2 as fa,

'no' as fb

union all

select 3 as fa,

'x' as fb

), cte21 as (

/*新增存在標準*/

select a.*,

(case when (select count(1

) from cte1 x where x.fc = a.fb)

>

0 then 1

else

0 end) as fexist

from cte2 a

)select x1.fa,

x1.fb,

x1.fc,

(case when x2.fexist =

1 then x2.fa

else null

end) as fa2,

(case when x2.fexist =

1 then x2.fb

else null

end) as fbc

from cte1 x1

left join cte21 x2 on x2.fa = x1.fa

二、

with cte1 as (

/*測試資料1*/

select 1 as fa,

'a' as fb,

'c' as fc

union all

select 2 as fa,

'b' as fb,

'd' as fc

union all

select 3 as fa,

'c' as fb,

'x' as fc

), cte2 as (

/*測試資料2*/

select 1 as fa,

'c' as fb

union all

select 2 as fa,

'no' as fb

union all

select 3 as fa,

'x' as fb

), cte21 as (

/*1)新增存在標準*/

select a.*,

(case when (select count(1

) from cte1 x where x.fc = a.fb)

>

0 then 1

else

0 end) as fexist

from cte2 a

), ctepout as (

/*2)關聯,不存在的顯示為null*/

select x1.fa,

x1.fb,

x1.fc,

(case when x2.fexist =

1 then x2.fa

else null

end) as fa2,

(case when x2.fexist =

1 then x2.fb

else null

end) as fbc

from cte1 x1

left join cte21 x2 on x2.fa = x1.fa

)/*輸出結果*/

select *

from ctepout;

三、mysql5.6

/*2)關聯,不存在的顯示為null*/

select x1.fa,

x1.fb,

x1.fc,

(case when x2.fexist =

1 then x2.fa else null end) as fa2,

(case when x2.fexist =

1 then x2.fb else null end) as fb2

from cte1 x1

left join (

select a.*,

(case when (select count(1

) from cte1 x where x.fc = a.fb)

>

0 then 1

else

0 end) as fexist

from cte2 a

) x2 on x2.fa = x1.fa

excel中兩列匹配,取匹配列的後一列資料

剛在處理excel資料時,遇到如下問題 已知a列的英文名和b列的中文名,現有一批c列的英文名,想根據a b列的對應規則,輸出c列對應的中文名。但是c列的順序和a列順序不一致,也不一定所有內容都被包含在a列。舉例 a b c d prvnce name 省名稱 accs nbr latn name 本...

mysql互換表中兩列資料

mysql互換表中兩列資料 update product set original price price,price original price 上面sql語句顯然不可取 因為先執行original price price original price的值已經更新為price,然後執行price...

mysql互換表中兩列資料

在開發過程中,有時由於業務等需要把乙個表中的兩列資料進行交換。解決方案 使用update命令,這完全得益於mysql sql命令功能的強大支援。中原來資料類似如下 select from product id name original price price 1 雪糕 5.00 3.50 2 鮮花...