Im running a query like below.
SELECT DISTINCT c.`id`
, c.`job-cat`
, (
SELECT COUNT(*)
FROM `jobs` j
WHERE j.`mul_category` IN (c.`id`)
AND j.`ending` >= DATE (NOW())
) AS jobCount
FROM `jobscat` c
WHERE (
SELECT COUNT(*)
FROM `jobs` j
WHERE j.`mul_category` IN (c.`id`)
AND j.`ending` >= DATE (NOW())
) > '0'
ORDER BY (
SELECT COUNT(*)
FROM `jobs` j
WHERE j.`mul_category` IN (c.`id`)
AND j.`ending` >= DATE (NOW())
) DESC
from the above query this
SELECT COUNT(*)
FROM `jobs` j
WHERE j.`mul_category` IN (c.`id`)
AND j.`ending` >= DATE (NOW())
repeated thrice, so my query planner also needs to execute this query 3times.
Since alias names will not work in where, so how can I optimize this query instead of running thrice I want to run only one time.
In order by I can use alias to reduce one step.
Best Answer
Turn it around so that you start with the grouping:
Indexes: