-1
I use a query within PHP to display the list of related categories and subcategories, get back more than 10,000 results (right) in 3 seconds on average, but after I implemented a subquery to check the amount of related subcategories, the query oscillated between 15-17 seconds.
No SUBQUERY (3s on average):
$sql_query = "SELECT t.* FROM `table` t
WHERE
t.`tbl_id` = '".mysqli_fetch_array($dbconn,$id)."'
ORDER BY
(CASE WHEN t.`tbl_nome` = 'Outros' THEN 1 ELSE 0 END) ASC,
t.`tbl_nome` ASC;
With SUBQUERY (15> on average):
$sql_query = "SELECT t.*,
(SELECT COUNT(n.`tbl_id`) FROM `categoria` n WHERE n.`tbl_pai` = t.`tbl_id` LIMIT 1)
AS `numSubs`
FROM
`table` t
WHERE
t.`tbl_id` = '".mysqli_fetch_array($dbconn,$id)."'
ORDER BY
(CASE WHEN t.`tbl_nome` = 'Outros' THEN 1 ELSE 0 END) ASC,
t.`tbl_nome` ASC;
I added COUNT to check for other records in the field tbl_pai
has different NULL ID and is the ID of the category to be consulted.
DOUBT:
There is another way to check if other fields have the current category ID in the field tbl_pai
1 only, which has the parent field with the current category ID. ? So optimize the query and stop slowing down?
Right, and what’s the question? :)
– Filipe L. Constante
Can post table structure?
– Filipe L. Constante
I got it, attached to the question =)
– ElvisP
The worst is that the query is within a looping, and could not be done differently for the requested purpose.
– ElvisP
What is the problem with the negativity of the question? At least they do not justify why.
– ElvisP
Possibly negative before you edit.
– Filipe L. Constante
It’s much easier if you post what you have inside the tables (at least as an example) and what you want to get. It gets very complicated to give an answer without having to test or having to invent data to test
– Sorack
@Sorack is that they are sensitive data, but they have some 10k+ and the structure is this only, the related data are in other tables but they are not used in this part of the code.
– ElvisP
@Eliseub. If you do not question or put example data, that do not need to be the real ones but only that demonstrate your problem I will not make a point of trying to answer too. The least you could do is make it easier for those who try to help you.
– Sorack
@Sorack the problem is in the query, which dropped the performance when running it, does not need data, it is not data, it is more an optimization of it (query) or other relationship mode, I left well explained what is happening. Thank you!
– ElvisP
@Eliseub. and how can anyone suggest an improvement of
query
ensuring that the data will not be altered?– Sorack
you need to use EXPLAIN and post the result, so just know where is the performance problem
– HudsonPH
@Sorack the data will not be changed, are permanent data, I made the suggested improvement and then I made a DB cache system in static HTML, what changes is the product table, but it is good the performance there, this I do not need to worry, and the suggestion of INDEX.
– ElvisP