所以如果我有两个表:
**Table_1:**
F_name |L_Name
GREGORY| WASHINGTON
**Table_2:**
ID_Key | Group_number
9233443GREG| 193556
我想将表2的ID_Key(GREG)的最后一位与表1的f_name(GREGORY)匹配。
因此,我希望输出显示ID_Key的后4位与F_name的前4位之间的所有匹配项。
这是我尝试过的方法,但无济于事:
select * from
Table_2 where
Where LEFT(ID_key,4) IN (
Select Left(F_name,4) from table_1
Group By LEFT (ID_KEY,4)
Having Count(*) > 1
)
有什么想法吗?
答案 0 :(得分:2)
那样简单吗?
select *
from table_1
inner join table_2 on left(table1.f_name, 4) = right(table_2.id_key, 4);
答案 1 :(得分:0)
在对第二张表进行ID_key细分时使用right
select * from
Table_2 where
Where right(ID_key,4) IN (
Select Left(F_name,4) from table_1
)
不需要您在查询中使用的聚合
输出
ID_key Group_number
9233443GREG 193556
答案 2 :(得分:0)
SELECT *
FROM [Table1] AS [t1]
INNER JOIN [Table2] AS [t2]
ON LEFT(t1.[F_Name],4) = RIGHT(t2.[ID_key],4);
答案 3 :(得分:0)
我们可以使用联接操作,并将匹配条件放入ON
子句中,如下所示:
SELECT r.id_key
, r.group_number
, n.f_name
, n.l_name
FROM `Table_1` n
JOIN `Table_2` r
ON RIGHT(TRIM(r.id_key),4) = LEFT(n.f_name,4)
ORDER
BY r.id_key
, r.group_number
, n.f_name
答案 4 :(得分:0)
您可以使用EXISTS:
select * from Table_2 t2
where exists (
select 1 from Table_1
where left(F_name, 4) = right(t2.ID_Key, 4)
)