【问题标题】:Postgresql get the distinct count when using limit and offsetPostgresql 在使用限制和偏移时获取不同的计数
【发布时间】:2021-08-30 17:49:22
【问题描述】:

我只是想知道在选择连接的多行查询并在 postgresql 中使用限制和偏移作为分页时是否有一种简单的方法来获得不同的计数。

例如,我有 3 个表,学生、教师以及学生和教师之间的关系表。

学生桌:

id name
1 Student1
2 Student2
3 Student3
4 Student4
5 Student5
6 Student6
7 Student7
8 Student8
9 Student9

...等等,直到 Student100

教师桌:

id name
1 Teacher1
2 Teacher2
3 Teacher3

student_teacher 表:

id studentId teacherId
1 1 1
2 1 2
3 1 3
4 2 1
5 2 2
6 2 3

...以此类推,直到所有 100 名学生都与教师 1、教师 2 和教师 3 在一起

这是我当前的 sql 查询:

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

“total_count”应该是 300,但我希望它是 100,因为只有 100 个不同的学生(我可以看到只有 100 行)。

有没有简单的方法来实现这一点?任何帮助将不胜感激。

【问题讨论】:

  • 请注意,distinct 不是函数。它始终适用于选择列表中的所有列。用括号括住一个(或多个)列不会改变任何东西并且是无用的。 distinct (a),bdistinct a,(b)distinct a,b 相同,distinct (t.*), xdistinct t.*, x 相同

标签: postgresql


【解决方案1】:

在将student_teacher 表过滤为teacherId = 2 后使用COUNT() 窗口函数,然后加入students

SELECT s.*, st.total_count  
FROM student s
JOIN (
  SELECT *, COUNT(*) OVER() AS total_count 
  FROM student_teacher 
  WHERE teacherId = 2
) st ON st.studentId = s.id
LIMIT 10 OFFSET 0;

无需加入teachers

【讨论】:

  • 啊,是的,我是在简化查询,原来的查询有不止一个关系表,所以我需要加入到教师表..但我目前正在考虑如何合并上述查询到我的可重用函数..
  • 实际上,当我运行内部 JOIN (select *, count( *) over() as total_count) 时,我仍然得到 300 作为总数,所以也许这不起作用..跨度>
  • @GlenK WHERE teacherId = 2 先应用,然后COUNT(*) OVER() 计算学生人数。所以,如果你有 300 名,那么 teacherId = 2 就有 300 名学生。有没有老师重复学生的情况?
  • 我明天再看一遍..正如我所说,我正在简化查询,所以我的查询可能有问题..会让你知道它是怎么回事..谢谢
  • 我发现了问题.. 在实际查询中,我使用了 LEFT JOIN 到另一个表,并且在 where 子句中我也有“IS NOT NULL”.. 也许我应该修复查询或发布另一个问题,因为在简单查询的情况下您的答案是正确的..
【解决方案2】:

也许这就是您正在寻找的答案。

SELECT DISTINCT(student.*),(select count(DISTINCT(student_id)) from student_teacher) 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

【讨论】:

  • (select count(*) from student) as total_count 会给出学生数=100,即使我删除了一个与teacher2的学生关系
  • @GlenK 我编辑了我的答案。现在计数在“student_teacher”表上。
猜你喜欢
  • 1970-01-01
  • 2018-02-16
  • 1970-01-01
  • 2021-03-26
  • 1970-01-01
  • 2019-09-06
  • 1970-01-01
  • 1970-01-01
  • 2019-12-25
相关资源
最近更新 更多