任何人都可以帮助我使用Mysql子查询?

时间:2018-05-31 17:29:50

标签: mysql subquery

这是我的查询:

SELECT id, lastname, firstname,

( SELECT COUNT( courses.id )
FROM courses
LEFT JOIN members_courses
ON courses.id = members_courses.course_id
WHERE members_courses.member_id = members.id ) as attended_courses

FROM members

LIMIT 10;

它工作正常,但现在我只需要选择在attend_courses = 0;

的行

我该怎么做?

三江源!

3 个答案:

答案 0 :(得分:0)

尝试类似这样的想法是让子查询作为一个表工作,这样你可能需要将member.id = member_courses.memeber_id置于子查询之外,尝试两种方式。:

SELECT id, lastname, firstname,cnt 
from  ( SELECT COUNT( courses.id ) as cnt FROM courses 
        LEFT JOIN members_courses ON courses.id = members_courses.course_id
        WHERE members_courses.member_id = members.id ) attended_courses, 
members 
where cnt=0 ;

答案 1 :(得分:0)

HAVING关键字用于后处理,类似于WHERE,用于预处理。

SELECT id, lastname, firstname,

( SELECT COUNT( courses.id )
FROM courses
LEFT JOIN members_courses
ON courses.id = members_courses.course_id
WHERE members_courses.member_id = members.id ) as attended_courses

FROM members
HAVING attended_courses=0
LIMIT 10;

答案 2 :(得分:0)

您可以使用连接重写您的查询

SELECT m.id, m.firstname, m.lastname , COUNT( courses.id ) attended_courses
FROM members m
LEFT JOIN members_courses mc ON mc.member_id = m.id
LEFT JOIN courses c ON c.id = mc.course_id
GROUP BY m.id, m.firstname, m.lastname
HAVING  attended_courses = 0