I am trying to retrieve rows from my database table, and prefer they have a provider_count
of higher then 0. I want to retrieve records with a provider_count
lower then 0 as the last results.
I'm currently using the following query on a table with around 1M records:
SELECT
`products`.*
FROM
`products`
WHERE
`products`.`provider_count` IN
(12,2,3,4,5,6,7,8,9,10,11,13,14,18,19,21,22,42,46,58,0)
GROUP BY
`products`.`search_name`
ORDER BY
FIELD(provider_count, 12,2,3,4,5,6,7,8,9,10,11,13,14,18,19,21,22,42,46,58,0)
LIMIT 48
Unfortunately the order by makes the query really slow, there is already an index on the provider_count column and I've tried adding an index to provider_count+search_name but that didn't show any improvements regarding the speed.
I've also tried to change the order by removing the WHERE statement and changing the ORDER BY to:
ORDER BY `products`.`provider_count` = 0 ASC, `products`.`provider_count`
But that results in quite the same execution time (give or take 5 seconds). Without the order by, query execution time is only 0.005s
Any suggestions on how I can improve this query?
Schema of my products table: https://www.db-fiddle.com/f/azBzXiRRsLtXCmLDCVe9DP/0
I'm going to try to answer - it's still not totally clear what your query is supposed to do. The Fiddle you provide doesn't run your query (due to the GROUP BY bug @rickJames mentioned).
I believe your intent is to retrieve every record in the products table, for a list of providers. You want the records where the provider is 0 to be at the end of that list. You want the query to perform quickly.
You should be able to achieve that via this query:
SELECT
`products`.*, 1 as no_provider
FROM
`products`
WHERE
`products`.`provider_count` IN
(12,2,3,4,5,6,7,8,9,10,11,13,14,18,19,21,22,42,46,58)
union
SELECT
`products`.*, 2 as no_provider
FROM
`products`
WHERE
`products`.`provider_count` = 0
order by no_provider, provider_count
LIMIT 48
Your limit clause means that if there are more than 48 records with a provider count > 0, the last clause won't show in your result set.
You could, of course, keep it even simpler:
SELECT
`products`.*
FROM
`products`
WHERE
`products`.`provider_count` IN
(12,2,3,4,5,6,7,8,9,10,11,13,14,18,19,21,22,42,46,58,0)
ORDER BY provider_count desc
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.