Answer the question
In order to leave comments, you need to log in
How to correctly write a condition for LEFT JOIN using COUNT for COUNT?
Dear gurus, lack of knowledge in SQL? help me please. I'm using Mysql 5. The query ideally looks like this:
SELECT r.*, r.`seats`- COUNT(re.`id`) as seatsFree FROM `tours` as r
LEFT JOIN `requests` as re ON re.`tour_id`=r.`id` and re.`visible`=1 and re.`status`=3
WHERE COUNT(re.`id`)>5
group by r.`id`
WHERE COUNT(re.`id`)>5
Answer the question
In order to leave comments, you need to log in
decided like this:
SELECT r.*, r.`seats`- COUNT(re.`id`) as seatsFree FROM `tours` as r
LEFT JOIN `requests` as re ON re.`tour_id`=r.`id` and re.`visible`=1 and re.`status`=3
WHERE 1
group by r.`id`
HAVING (seatsFree <=90)
ORDER BY r.`finished` DESC
LIMIT 0,2
SELECT COUNT(r.id) as num, r.`seats`- COUNT(re.`id`) as seatsFree FROM `tours` as r
LEFT JOIN `requests` as re ON re.`tour_id`=r.`id` and re.`visible`=1 and re.`status`=3 WHERE 1 group by r.`id` HAVING (seatsFree <=90) order by num desc
LIMIT 1
I haven't looked at the gist, but maybe something like this:
SELECT r.*, r.`seats`- COUNT(re.`id`) as seatsFree FROM `tours` as r
LEFT JOIN `requests` as re ON re.`tour_id`=r.`id` and re.`visible`=1 and re.`status`=3
group by r.`id`
having COUNT(re.`id`)>5
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question