加入喜欢并防止出现多个结果
Join with like and prevent multiple results
我想在联接中加入 2 table 和类似的搜索值(只会比较前 4 个字符串)。但结果应该只有 1:1,我想防止主 table.
中的 1 个条目出现多个结果
tab1
name
jackson
michael
tab2
name
code
JACK
12345
JACK X
67890
Micha
12000
Michael T.
90000
结果
name_tab1
code_tab2
jackson
12345
michael
12000
对于选项卡 1 中的每个条目,我得到了多个结果。
Select * from tab1
left outer join tab2 on lower(substr(tab1.name,1,4) like '%'||substr(trim(lower(tab2.name)),1,4)||'%'
如果不介意code
拿什么,可以按name
分组,拿code
的max/min。类似于:
select tab1.name, max(tab2.code)
from tab1
left outer join tab2 on lower(substr(tab1.name,1,4) like '%'||substr(trim(lower(tab2.name)),1,4)||'%'
group by tab1.name
试试这个:
WITH
TAB1 (NAME) AS
(
VALUES
'jackson'
, 'michael'
, 'Jack Daniels'
, 'Michelin'
)
, TAB2 (NAME, CODE) AS
(
VALUES
('JACK', '12345')
, ('JACK X', '67890')
, ('Micha', '12000')
, ('Michael T.', '90000')
)
SELECT A.NAME, B.CODE
FROM TAB1 A
LEFT JOIN TABLE
(
SELECT B.CODE
FROM TAB2 B
WHERE
LOWER (SUBSTR (A.NAME, 1, 4))
LIKE '%' || LOWER (SUBSTR (B.NAME, 1, 4)) || '%'
FETCH FIRST 1 ROW ONLY
) B ON 1 = 1
NAME
CODE
jackson
12345
michael
12000
Jack Daniels
12345
Michelin
12000
我想在联接中加入 2 table 和类似的搜索值(只会比较前 4 个字符串)。但结果应该只有 1:1,我想防止主 table.
中的 1 个条目出现多个结果tab1
name |
---|
jackson |
michael |
tab2
name | code |
---|---|
JACK | 12345 |
JACK X | 67890 |
Micha | 12000 |
Michael T. | 90000 |
结果
name_tab1 | code_tab2 |
---|---|
jackson | 12345 |
michael | 12000 |
对于选项卡 1 中的每个条目,我得到了多个结果。
Select * from tab1
left outer join tab2 on lower(substr(tab1.name,1,4) like '%'||substr(trim(lower(tab2.name)),1,4)||'%'
如果不介意code
拿什么,可以按name
分组,拿code
的max/min。类似于:
select tab1.name, max(tab2.code)
from tab1
left outer join tab2 on lower(substr(tab1.name,1,4) like '%'||substr(trim(lower(tab2.name)),1,4)||'%'
group by tab1.name
试试这个:
WITH
TAB1 (NAME) AS
(
VALUES
'jackson'
, 'michael'
, 'Jack Daniels'
, 'Michelin'
)
, TAB2 (NAME, CODE) AS
(
VALUES
('JACK', '12345')
, ('JACK X', '67890')
, ('Micha', '12000')
, ('Michael T.', '90000')
)
SELECT A.NAME, B.CODE
FROM TAB1 A
LEFT JOIN TABLE
(
SELECT B.CODE
FROM TAB2 B
WHERE
LOWER (SUBSTR (A.NAME, 1, 4))
LIKE '%' || LOWER (SUBSTR (B.NAME, 1, 4)) || '%'
FETCH FIRST 1 ROW ONLY
) B ON 1 = 1
NAME | CODE |
---|---|
jackson | 12345 |
michael | 12000 |
Jack Daniels | 12345 |
Michelin | 12000 |