Sql 在精确字符串或截断字符串上联接表
好吧,这可能是一个很难回答的问题。我想在两个条件下连接ID上的两个表:Sql 在精确字符串或截断字符串上联接表,sql,Sql,好吧,这可能是一个很难回答的问题。我想在两个条件下连接ID上的两个表: 精确匹配 前3个字符匹配后的字符 还有,是否有更好的方式显示表格 表1: Comp ID Year 94372 2016 P1983 2011 874324 2015 0342135 2013 732423 2015 表2: ID User 30094372 TYVSW
Comp ID Year
94372 2016
P1983 2011
874324 2015
0342135 2013
732423 2015
表2:
ID User
30094372 TYVSW
2000342135 PFDBE
100732423 PLECD
P1983 ASNWQ
联接表
T1CompID T1Year T2ID T2User
94372 2016 30094371 TYVSW
P1983 2011 P1983 ASNWQ
874324 2015 Null Null
0342135 2013 2000342135 PFDBE
732423 2015 100732423 PLECD
如果第一个表的ID与第二个表的ID完全匹配,或者第一个表的ID与第二个表的第四个字符的子字符串匹配,则执行
左联接
SELECT t1."Comp ID" AS T1CompID,
t1.Year AS T1Year,
t2.ID AS T2ID,
t2.User AS T2User
FROM table1 t1
LEFT JOIN table2 t2
ON t1."Comp ID" = t2.ID OR -- exact match
t1."Comp ID" = SUBSTRING(t2.ID, 4) -- match from fourth character of t2.ID
对于SQL Server,您可能需要使用[Comp ID]
来转义此列名。试试这个
SELECT * FROM tb1 t1
LEFT JOIN tb2 t2
ON IF(length(t1.ID) = length(t2.ID),t1.ID = t2.ID,substring(t2.ID,4) = t1.ID);
+---------+------+------------+-------+
| ID | Year | ID | User |
+---------+------+------------+-------+
| 94372 | 2016 | 30094372 | TYVSW |
| 0342135 | 2013 | 2000342135 | PFDBE |
| 732423 | 2015 | 100732423 | PLECD |
| P1983 | 2011 | P1983 | ASNWQ |
| 874324 | 2015 | NULL | NULL |
+---------+------+------------+-------+
5 rows in set (0.00 sec)
为了提高性能,您可能需要使用两个左连接:
select t1.compid, t1.year,
coalesce(t2e.id, t2p.id) as t2id
coalesce(t2e.user, t2p.user) as t2.user
from table1 t1 left join
table2 t2e
on t1.compid = t2.compid left join
table2 t2p
on t1.compid = substring(t2p.id, 4, 100) and
t2e.compid is null;
从第4个字符开始获取值的精确表达式因数据库而异
这种方法的一个优点是,即使第二个表中有两行匹配,它也只会返回完全匹配。您没有提到正在使用的数据库服务器。您可以在JOIN中使用子字符串或类似函数。或者最好再创建一列(可能是一个计算列)来保存前3个字符,并在联接中使用Or。您使用的是哪种DBMS?我使用的是Oracle。
SELECT t1."Comp ID" AS T1CompID,
t1.Year AS T1Year,
t2.ID AS T2ID,
t2.User AS T2User
FROM table1 t1
LEFT JOIN table2 t2
ON t1."Comp ID" = t2.ID OR -- exact match
t1."Comp ID" = SUBSTRING(t2.ID, 4) -- match from fourth character of t2.ID