4

I've been searching the questions but haven´t found an answer. I would like to do an inner join with Table 1 and Table 2 , but one field is INT and other is VARCHAR (with the structure "A-INT"). Something like:

    Table1                    Table2

    ID NAME   WHATEVER        ID USER
    1  A-001  ---             1  001 
    2  A-002  ---             2  002
    3  A-003  ---             3  003
    3  A-004  ---             4  004  
    ...

How can I construct the query? Something like:

... Table1 INNER JOIN Table2 ON Table1.NAME = Table2.[A-USER] ...
4

3 回答 3

9

您需要将int值转换为varchar并将其与 连接'A-',或者获取值的数字部分varchar并转换为int

根据您使用的数据库,这会有所不同,对于 SQL Server,它看起来像这样:

select t1.ID, t1.WHATEVER, t2.USER
from Table1 t1
inner join Table2 t2 on t2.ID = cast(substring(t1.NAME, 3, 3) as int)
于 2012-10-09T07:25:45.877 回答
0

通过串联尝试,

SELECT *
FROM Table1 a, Table2 b
WHERE a.Name = 'A-' + b.User

但请注意,这会降低性能。

于 2012-10-09T07:23:15.987 回答
-3

您想在 Table1.NAME = Table2.[A-USER] 上进行内部联接。

如果 Table1.NAME、Table2.[A-USER] 列数据类型不同,则不能使用内连接。

于 2012-10-09T07:26:06.390 回答