简体   繁体   中英

How to join two tables on fields that are not formatted the same

I have two tables containing a string field that in one table is six bytes long, and in the other table is seven bytes long, because of the insertion of a hyphen between the first two bytes and the last four bytes. The two fields look like this: AB1234 and AB-1234. I tried a join like this:

    FROM       TableA ta
    INNER JOIN TableB tb ON Left(ta.fld, 2) + '-' + Mid(ta.fld, 3) = tb.fld

...and I tried

    FROM       TableA ta
    INNER JOIN TableB tb ON Left(ta.fld, 2) = Left(tb.fld, 2) AND Mid(ta.fld, 3) = Mid(tb.fld, 4)

...but neither works. Is there a way to do this with a subquery? Is there another approach?

How about using REPLACE to remove the dash before comparing:

SELECT *
FROM TableA a
INNER JOIN TableB b
    ON a.fld = REPLACE(b.fld, "_", "");

使用 RIGHT 而不是 MID

Left(ta.fld, 2) + '-' + RIGHT(ta.fld, 4) = tb.fld

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM