简体   繁体   中英

is there a better way to write this query

I am trying to search and update record which start which a partcular number or fall with a range.

I have made a query which works where values start with a particular number. I can't figure out how to do it with a range.

for example I want to update the following values in products_ean with " "

255
201-230   ---> starts with 201,202,203 ...230
236
980-990   ---> starts with 980.981,982 ...990

I have written the following query which works but not sure if it is efficent espcialy when it has to serach over 100k records. It doesn't work with range.

UPDATE products SET products_ean ="" 
where products_ean like "200%" 
OR products_ean like "020%" 
OR products_ean like "023%" 
OR products_ean like "027%" 
OR products_ean like "042%" 
OR products_ean like "221%" 
OR products_ean like "209%" 
OR products_ean like "041%" 
OR products_ean like "049%" 
OR products_ean like "026%" 
OR products_ean like "025%" 
OR products_ean like "299%";

This will be a full table scan anyhow, so you can use a function on products_ean with no loss of performance. This said, you can get the query more readable, but probably not much faster. However, you can still try whether it is faster, to take the three leading digits and compare these:

UPDATE products SET products_ean = '' 
where left(products_ean,3) in ('200', '020', '027', ...);

If you find it more readable, you can even use ranges:

UPDATE products SET products_ean = '' 
where left(products_ean,3) = '255'
   or left(products_ean,3) between '201' and '230'
...

maybe you could try this not sure about performance but less code.. if your ean is a string field. you can try this

UPDATE products SET products_ean ="" 
where (left(products_ean,3) between 201 and 230) or
(left(products_ean,3) between 980 and 990) or

PS: you might want to cast the field.

I don't think its going to be faster but its another alternative:

To Find:

SELECT * 
FROM products
WHERE products_ean
REGEXP  '^(200|020|023|027|042|221|209|041|049|026|025|299)'

To Replace:

UPDATE products SET products_ean = ''
WHERE products_ean
REGEXP  '^(200|020|023|027|042|221|209|041|049|026|025|299)'

note: it will not use indexes

You can try this

UPDATE products SET products_ean = " "
WHERE STRCMP(products_ean, '200') >= 0 AND STRCMP(products_ean, '220') <= 0

你可以尝试在哪里包含,它必须像:

WHERE CONTAINS(t.products_ean, '"200*" OR "020*" OR "023*"')

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