gpt4 book ai didi

mysql 返回带有随机重复值的错误结果

转载 作者:行者123 更新时间:2023-11-29 12:05:42 24 4
gpt4 key购买 nike

我需要从表格中返回每个类别中最好的 5 个分数。到目前为止,我已尝试按照以下网站的示例进行查询:selecting top n records per group

查询:

select  
subject_name,substring_index(substring_index
(group_concat(exams_scores.admission_no order by exams_scores.score desc),',',value),',',-1) as names,
substring_index(substring_index(group_concat(score order by score desc),',',value),',',-1)
as orderedscore
from exams_scores,students,subjects,tinyint_asc
where tinyint_asc.value >=1 and tinyint_asc.value <=5 and exam_id=2
and exams_scores.admission_no=students.admission_no and students.form_id=1 and
exams_scores.subject_code=subjects.subject_code group by exams_scores.subject_code,value;

我得到了我需要的前n个,但我的问题是它随机返回重复项,我不知道它们来自哪里

如您所见,英语和数学有不应该存在的重复项

+------------------+-------+--------------+
| subject_name | names | orderedscore |
+------------------+-------+--------------+
| English | 1500 | 100 |
| English | 1500 | 100 |
| English | 2491 | 100 |
| English | 1501 | 99 |
| English | 1111 | 99 |
|Mathematics | 1004 | 100 |
| Mathematics | 1004 | 100 |
| Mathematics | 2722 | 99 |
| Mathematics | 2734 | 99 |
| Mathematics | 2712 | 99 |
+-----------------------------------------+

我已检查表格,不存在重复项

确认表中没有重复项:

select * from exams_scores 
having(exam_id=2) and (subject_code=121) and (admission_no=1004);

结果:

+------+--------------+---------+--------------+-------+
| id | admission_no | exam_id | subject_code | score |
+------+--------------+---------+--------------+-------+
| 4919 | 1004 | 2 | 121 | 100 |
+------+--------------+---------+--------------+-------+
1 row in set (0.00 sec)

英语的结果相同。

如果我运行查询 5 次,有时我会得到另一个具有重复值的字段。

谁能告诉我为什么我的查询会这样......我尝试在内部添加不同

group_concat(ditinct(exams_scores.admission_no))

但这没有用??

最佳答案

您将按 exams_scores.subject_code, value 进行分组。如果您将它们添加到所选列(...asorderscore, exams_scores.subject_code, value from...),您应该看到所有行相对于您分组的这两列都是不同的。以下哪项是 GROUP BY 的正确语义。

编辑,澄清:

  1. 首先,SQL Server 根据您的 WHERE 子句删除一些行。
  2. 然后,它会根据您的 GROUP BY 子句对剩余的行进行分组。
  3. 最后,它会选择您指定的列,方法是直接返回列的值或对某些列执行 GROUP_CONCAT 并返回其累计值。

如果您选择的列未包含在 GROUP BY 子句中,则这些列的返回结果是任意的,因为 SQL Server 会减少与 中指定的列相等的所有行。 GROUP BY 子句到一行 - 至于其余列,结果几乎是未定义的(因此您遇到的“随机性”),因为 - 服务器应该选择什么作为该列的值?它只能从所有减少的行中随机选择一行。

事实上,某些 SQL 服务器不会执行此类查询并返回 SQL 错误,因为这些列的结果是未定义的,这是您通常不希望出现的情况。使用这些服务器(我相信 MSSQL 就是其中之一),您或多或少只能在 SELECT 子句中包含作为 GROUP BY 子句一部分的列。 p>

编辑 2:最后,这意味着您必须优化 GROUP BY 子句以获得所需的分组。

关于mysql 返回带有随机重复值的错误结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31518206/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com