I'm just wondering if there is an easy way to get a distinct count when selecting a joined multiple rows query and using limit and offset as pagination in postgresql.
For example, I have 3 tables, student, teacher, and relational table between the student and teacher.
student table:
| id | name |
|---|---|
| 1 | Student1 |
| 2 | Student2 |
| 3 | Student3 |
| 4 | Student4 |
| 5 | Student5 |
| 6 | Student6 |
| 7 | Student7 |
| 8 | Student8 |
| 9 | Student9 |
... and so on up to Student100
teacher table:
| id | name |
|---|---|
| 1 | Teacher1 |
| 2 | Teacher2 |
| 3 | Teacher3 |
student_teacher table:
| id | studentId | teacherId |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 1 | 3 |
| 4 | 2 | 1 |
| 5 | 2 | 2 |
| 6 | 2 | 3 |
... and so on until all 100 students are with teacher1, teacher2, and teacher3
Here is my current sql query:
SELECT DISTINCT(student.*), COUNT(*) OVER() AS "total_count" from student
JOIN student_teacher on student_teacher.studentId = student.id
JOIN teacher on student_teacher.teacherId = teacher.id
WHERE teacher.id = 2
LIMIT 10 OFFSET 0
the "total_count" would be 300, but I want it to be 100 instead because there are only 100 distinct student (I can see that there are only 100 rows).
Is there an easy way to achieve this? Any help would be much appreciated.
distinctis not a function. It always applies to all columns in the select list. Enclosing one (or more) of the columns with parentheses won't change anything and is useless.distinct (a),bis the same asdistinct a,(b)ordistinct a,banddistinct (t.*), xis the same asdistinct t.*, x