当列数等于1或2时,如何将两个表的结果查找为唯一


How to find result of two table as unique when count of column equal one or two?

我有两个表,一个是学生的名字,另一个有学生的课,我需要找到有两节或一节课的学生。

table 1 :(students)
id , name , family , birth , mobile
table 2 : (lessons)
id , studentID , name 

我的代码是

SELECT t.* FROM students AS t LEFT JOIN lessons AS tr ON t.id = tr.userID WHERE count(tr.*) = 1

这是您的查询:

SELECT students.name, COUNT(studentID) AS CANT FROM students, lessons WHERE students.id = studentID GROUP BY studentID HAVING CANT = 1 OR CANT = 2

试试这个

SELECT s.id , s.name , family , birth , mobile FROM student s, lessons l WHERE s.id = l.studentID AND (SELECT COUNT(*) FROM lessons WHERE studentID = student.id) as totalLessons BETWEEN 1 AND 2 GROUP BY s.id