简体   繁体   中英

Fastest way to compare two values in two tables

I need to match cities from two different tables. In both, I have the postcode and the name. But for example I have in one "BOURGES" & "18000" and in the other one "BOURGES CEDEX" & "18006".

I tried in a first time this :

INNER JOIN b_agence ag ON ag.ville = c.li_commune AND ag.code_postal = c.cd_postal

I changed it to :

INNER JOIN b_agence a ON (trim(c.li_commune) = trim(replace(a.VILLE,'CEDEX','')) AND left(a.CODE_POSTAL,2) = left(c.cd_postal,2) )

It works but unfortunately my request is taking 30 seconds more, How can I achieved it in a fastest way ?

请使用存在代替联接从表1 t1中选择*在哪里存在(从第2个条件中的table2 t2选择顶部1 1)和存在(从第2个条件中的table2 t3中选择顶部1 1)

The problem is that by introducing the TRIM, you are forcing the SQL engine to do a full table scan (also including string manipulation) every time you do your query. If you want it to be fast, create a new field, like VILLE_TRIMMED and populate that one-time with your values with "CEDEX" removed (you may have to introduce a trigger to keep values up to date if they are being added or changed), index that new VILLE_TRIMMED field (and make sure your source li_commune field is indexed too, and your postal code fields in both tables), and join on that. Then your query can use the indexes to do the joins rather than doing a full table scan every time, and so will be some orders of magnitude faster.

You'll note that we're introducing some denormalisation here. It's a common pattern: normalise for keeping your data tidy; denormalise for speed.

If your database is SQL Server, you could do VILLE_TRIMMED as a computed column (doing your trimming of "CEDEX" off the end), and mark it as PERSISTED, and then join to that. Saves the trouble of triggers etc to keep the column up to date - the SQL Server engine will take care of that.

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