当列数等于一或二时,如何找到两个 table 的唯一结果?
How to find result of two table as unique when count of column equal one or two?
我有两个table,一个是学生姓名,另一个是上过课的学生,我需要找到上过两节课或一节课的学生。
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 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
这是您的查询:
SELECT students.name, COUNT(studentID) AS CANT FROM students, lessons WHERE students.id = studentID GROUP BY studentID HAVING CANT = 1 OR CANT = 2
我有两个table,一个是学生姓名,另一个是上过课的学生,我需要找到上过两节课或一节课的学生。
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 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
这是您的查询:
SELECT students.name, COUNT(studentID) AS CANT FROM students, lessons WHERE students.id = studentID GROUP BY studentID HAVING CANT = 1 OR CANT = 2