Hello everyone I have a complex query that creates unique feed of tenders for each user based on his/her interests, areas of activity, keywords, and budget ranges. Now I have 1M+ tenders and this query takes 30secods+ to execute how can it be rewritten in different more optimized manner?
SELECT
*
FROM
`tenders`
WHERE
(
`activity_field_id` IN(
SELECT
`activity_field_id`
FROM
`activity_field_user`
WHERE
`user_id` = '1'
) OR EXISTS(
SELECT
*
FROM
`lots`
WHERE
`tenders`.`id` = `lots`.`tender_id` AND EXISTS(
SELECT
*
FROM
`lot_items`
WHERE
`lots`.`id` = `lot_items`.`lot_id` AND `code_id` IN(
SELECT
`id`
FROM
`codes`
WHERE
`activity_field_id` IN(
SELECT
`activity_field_id`
FROM
`activity_field_user`
WHERE
`user_id` = '1'
)
)
)
) OR EXISTS(
SELECT
*
FROM
`activity_fields`
INNER JOIN `activity_field_tender` ON `activity_fields`.`id` = `activity_field_tender`.`activity_field_id`
WHERE
`tenders`.`id` = `activity_field_tender`.`tender_id` AND `activity_fields`.`id` IN(
SELECT
`activity_field_id`
FROM
`activity_field_user`
WHERE
`user_id` = '1'
)
) OR `organization_id` IN(
SELECT
`organization_id`
FROM
`organization_user`
WHERE
`user_id` = '1'
) OR(
`tenders`.`title` LIKE '%оборудование%'
) AND `public_time` BETWEEN '2022-04-03 00:00:00' AND '2022-05-03 23:59:59'
) AND `canceled_at` IS NULL AND `protocol_created_at` IS NULL AND `end_time` >= '2022-05-03 15:47:11' AND `public_time` >= '2022-04-03 00:00:00' AND `public_time` < '2022-05-03 23:59:59' AND NOT EXISTS(
SELECT
*
FROM
`black_lists`
WHERE
`tenders`.`id` = `black_lists`.`tender_id` AND `user_id` = '1'
) AND NOT EXISTS(
SELECT
*
FROM
`tender_works`
WHERE
`tenders`.`id` = `tender_works`.`tender_id` AND `user_id` = '1'
)
ORDER BY
`public_time` ASC
LIMIT 20 OFFSET 0;