Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a better way to write this query

Tags:

sql

mysql

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%";
like image 302
naf Avatar asked Nov 17 '14 10:11

naf


People also ask

What are the types of query?

It is commonly accepted that there are three different types of search queries: Navigational search queries. Informational search queries. Transactional search queries.


2 Answers

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'
...
like image 103
Thorsten Kettner Avatar answered Oct 11 '22 17:10

Thorsten Kettner


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.

like image 20
Krish Avatar answered Oct 11 '22 18:10

Krish