2

My tables are like this:

Table 1 (students)
Table 1

Table 2 (results)

Table 2

I want to select all students from Table 1 students who have 4 results in the results table. I tried this query, but with no success:

SELECT * 
FROM students
WHERE gender =  'm'
AND (SELECT COUNT( result ) AS count
FROM results
INNER JOIN students ON results.stuID = students.stuID
WHERE result !=0
) =4
ORDER BY rank ASC

3 Answers 3

4

You can rewrite your query by using join and HAVING clause to check the count for each student group ,This can be done without using the subquery which sometimes affects on performance

SELECT s.*,COUNT(*) AS count
FROM students s
INNER JOIN results r ON r.stuID = s.stuID
WHERE r.result !=0
GROUP BY s.stuID 
HAVING count =4
ORDER BY s.rank ASC
Sign up to request clarification or add additional context in comments.

1 Comment

As far as optimized query is concern its the best +1
1

um, that's a little convoluted. the where clause should come after the subquery, and the subquery still needs to be JOINed back to the main query.

something like

SELECT * FROM students 
INNER JOIN (SELECT COUNT(result),results.stuID as count FROM results WHERE result != 0) as result_count
ON result_count.stuID = students.stuID
WHERE result_count.count =4 AND students.gender = 'm'
ORDER BY rank ASC

Comments

0

You have to use alias for table also -

SELECT * 
FROM students as a
WHERE gender =  'm'
AND (SELECT COUNT(result) AS count
FROM results as b
WHERE b.stuID = a.stuID AND
(result!=0 OR result IS NOT NULL OR result!='')
) = 4
ORDER BY rank ASC

1 Comment

Working perfect! Thanks, I will accept your answer as soon as possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.