/    Sign up×
Community /Pin to ProfileBookmark

SELECT WHERE JOINED Table Count is greater than..

I’m trying to run a query which will show all students who have a status of 1 (active) and they’re in class type 1 (general role) or if they’re in more than 5 classes.

This is what I have. It works except I get students in 0-5 classes as well. So I guess it doesn’t work.

“`
SELECT s.ID, s.StudentName, (SELECT COUNT(*) AS ttl FROM Classes i WHERE i.StudenID = s.ID) As Qnty

FROM `students` s

WHERE s.StudentStatus= 1 AND s.ClassType = 1 OR (SELECT COUNT(*) AS ttl FROM Classes i WHERE i.StudentID= s.ID) > 5

ORDER BY `Qnty` ASC
“`

to post a comment
PHP

1 Comments(s)

Copy linkTweet thisAlerts:
@NogDogOct 21.2020 — Probably just need some parens:
<i>
</i> WHERE s.StudentStatus= 1 AND (s.ClassType = 1 OR (SELECT COUNT(*) AS ttl FROM Classes i WHERE i.StudentID= s.ID) &gt; 5)

That being said, I don't like seeing that same sub-query in two places, but you may need to do something like this, I _think_ (no promises ;) )...
<i>
</i>SELECT s.ID, s.StudentName, totals.total As Qnty
FROM students s
INNER JOIN ( -- Might need to be a LEFT JOIN???
SELECT StudentID, COUNT(*) AS total
FROM Classes c1
GROUP BY StudentID
) AS totals ON s.ID = totals.StudentID
WHERE s.StudentStatus= 1 AND (s.ClassType = 1 OR totals.total &gt; 5)
ORDER BY Qnty ASC
×

Success!

Help @kiwis spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.7,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...