Answer the question
In order to leave comments, you need to log in
What should be the MySQL query execution time?
Hello, help optimize the request to reduce the response time.
In general, there is a request for a selection of publications for a news feed similar to VK.
At the same time, there are categories and cities that the user can select.
One publication can be in several cities and in several categories.
And the last difficulty, there are categories and cities that can only be viewed by subscribers.
The structure is:
Publication:
id
--many fields--
Sities:
id
name
Categories:
id
name
Pub_kat
id
kat_id
pub_id
Pub_sity
id
sity_id
pub_id
In php I generate variables:
//выбранные категории, вернет строку типа - "1,2,3" исключая недоступные для юсера
$true_kat;
//выбранные города, вернет строку типа - "1,2,3" исключая недоступные для юсера
$true_sity;
//запрещенные для юсера категории, если он подписчик или их нет то вернет 0
$false_kat;
//запрещенные для юсера города, если он подписчик или их нет то вернет 0
$false_sity;
SELECT c.id, c.text, c.date, c.name,
(SELECT count(liked) FROM Likes_pub
WHERE liked = 1 and pub_id=c.id) as 'like',
(SELECT count(liked) FROM Likes_pub
WHERE liked = 0 and pub_id=c.id) as 'dislike'
FROM Publication c
WHERE c.id in
(SELECT pub_id FROM Pub_kat WHERE kat_id in ($true_kat) and pub_id in
(SELECT pub_id FROM Pub_sity WHERE sity_id in ($true_sity)))
AND
c.id not in
(SELECT pub_id FROM Pub_kat WHERE kat_id in ($false_kat) and pub_id not in
(SELECT pub_id FROM Pub_sity WHERE sity_id in ($false_sity)))
ORDER by c.id DESC LIMIT 0,20
SELECT c.name
FROM Publication c
WHERE c.id in
(SELECT pub_id FROM Pub_kat WHERE kat_id in ($true_kat) and pub_id in
(SELECT pub_id FROM Pub_sity WHERE sity_id in ($true_sity)))
AND
c.id not in
(SELECT pub_id FROM Pub_kat WHERE kat_id in ($false_kat) and pub_id not in
(SELECT pub_id FROM Pub_sity WHERE sity_id in ($false_sity)))
ORDER by c.id DESC LIMIT 0,20
Answer the question
In order to leave comments, you need to log in
I do not have in-depth knowledge of subd. Once I also made such nested queries, exactly the same ...IN(SELECT id... For some reason, I intuitively decided that it would be faster than making separate queries. And then I stumbled upon these brakes. For the experiment, I tried to make nested queries with different queries and then form the main one.It turned out to be faster than 400 times
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question