如何使用通配符连接两个表,仅给出表 1 中每行的最佳匹配
how to join two tables using wildcards giving only best match per row from table1
如何将在两个 table 之间使用通配符连接的查询的结果限制为从 table 1 开始的每行只有一个结果(最佳匹配)?
我有以下数据结构:
table t1:
ID AccountStr
1 7
2 71
3 72
4 721
5 73
6 8
table t2:
ID AccountPattern AccountType
1 7 Type01
2 72 Type02xxx
想要的查询结果:
Line AccountStr AccountType
1 7 Type01
2 71 Type01
3 72 Type02xxx
4 721 Type02xxx
5 73 Type01
6 8 NULL
我使用的代码(语法:MS Access SQL):
SELECT T1.AccountStr, T2.AccountType
FROM T1 LEFT JOIN T2 ON T1.AccountStr Like T2.AccountPattern+"*"
ORDER BY T1.AccountStr, T2.AccountType;
我的查询结果,标记为不需要的行:
Line AccountStr AccountType
1 7 Type01
2 71 Type01
3 72 Type01 **unwanted line**
4 72 Type02xxx
5 72 Type01 **unwanted line**
6 721 Type02xxx
7 73 Type01
8 8 NULL
我明白,为什么我的查询给出了所有匹配 - 72
匹配模式 7*
- 但是因为有更好的匹配模式 72*
我只需要在我的结果。
我考虑过 t2
的降序排序顺序 - AccountPattern 72
在 7
之前 - 并将模式匹配结果限制为仅第一行,但我不知道如何这样做 - 或者也许有更好的方法。
使用关联子查询 TOP 1
:
SELECT T1.AccountStr,
(SELECT TOP 1 T2.AccountType
FROM T2
WHERE T1.AccountStr Like T2.AccountPattern + "*"
ORDER BY LEN(T2.AccountPattern) DESC, T2.AccountPattern
) as AccountType
FROM T1
ORDER BY T1.AccountStr;
这个returns最长的匹配模式。
如何将在两个 table 之间使用通配符连接的查询的结果限制为从 table 1 开始的每行只有一个结果(最佳匹配)?
我有以下数据结构:
table t1:
ID AccountStr
1 7
2 71
3 72
4 721
5 73
6 8
table t2:
ID AccountPattern AccountType
1 7 Type01
2 72 Type02xxx
想要的查询结果:
Line AccountStr AccountType
1 7 Type01
2 71 Type01
3 72 Type02xxx
4 721 Type02xxx
5 73 Type01
6 8 NULL
我使用的代码(语法:MS Access SQL):
SELECT T1.AccountStr, T2.AccountType
FROM T1 LEFT JOIN T2 ON T1.AccountStr Like T2.AccountPattern+"*"
ORDER BY T1.AccountStr, T2.AccountType;
我的查询结果,标记为不需要的行:
Line AccountStr AccountType
1 7 Type01
2 71 Type01
3 72 Type01 **unwanted line**
4 72 Type02xxx
5 72 Type01 **unwanted line**
6 721 Type02xxx
7 73 Type01
8 8 NULL
我明白,为什么我的查询给出了所有匹配 - 72
匹配模式 7*
- 但是因为有更好的匹配模式 72*
我只需要在我的结果。
我考虑过 t2
的降序排序顺序 - AccountPattern 72
在 7
之前 - 并将模式匹配结果限制为仅第一行,但我不知道如何这样做 - 或者也许有更好的方法。
使用关联子查询 TOP 1
:
SELECT T1.AccountStr,
(SELECT TOP 1 T2.AccountType
FROM T2
WHERE T1.AccountStr Like T2.AccountPattern + "*"
ORDER BY LEN(T2.AccountPattern) DESC, T2.AccountPattern
) as AccountType
FROM T1
ORDER BY T1.AccountStr;
这个returns最长的匹配模式。