A
A
acspro2015-06-02 02:13:06
MySQL
acspro, 2015-06-02 02:13:06

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`

And naturally dies on the line:
WHERE COUNT(re.`id`)>5
Writes Invalid use of group function
I think that you need to write HAVING but how? How to make a request?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
acspro, 2015-06-02
@acspro

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

But now it is not clear how to calculate the number of samples
. Something like
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

But it works sloppy.

E
Evgeniy Zavyalov, 2015-06-02
@profit

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 question

Ask a Question

731 491 924 answers to any question