gpt4 book ai didi

mysql - SQL COUNT 没有给我正确的结果

转载 作者:行者123 更新时间:2023-11-29 07:29:25 25 4
gpt4 key购买 nike

所以,我有这个 articles 表,我想查找特定部分(例如第 1 部分)有多少篇已发表的文章。这是我使用的 SQL:

  SELECT count(*) as numStories 
FROM noticia WHERE not_flgpublicar = 'S' AND not_sec = 1;

我得到的结果:

+------------+
| numStories |
+------------+
| 0 |
+------------+

但这是不对的,因为我知道该部分存在并且该部分中有几篇已发表的文章。事实上,无论我使用哪个部分都无关紧要,SQL 始终返回零计数!

然后我这样做了:

 SELECT not_sec, count(*) as numStories 
FROM noticia WHERE not_flgpublicar='S' GROUP BY not_sec;

我得到的结果:

+---------+------------+
| not_sec | numStories |
+---------+------------+
| NULL | 8 |
| 0 | 3583 |
| 1 | 20151 |
| 2 | 15979 |
| 3 | 8233 |
| 4 | 8406 |
| 5 | 3493 |
| 6 | 3952 |
| 7 | 1237 |
| 8 | 1213 |
| 9 | 108 |
| 11 | 44 |
| 12 | 12 |
+---------+------------+

如您所见,每个部分都有几篇文章,但第一个 SQL 语句仍然无法运行。我找到了一种通过这样做来获得正确计数的方法:

SELECT count(*) as numStories 
FROM noticia WHERE not_flgpublicar='S' GROUP BY not_sec HAVING not_sec = 1;

(最终)返回:

+------------+
| numStories |
+------------+
| 20151 |
+------------+

但我真的非常想知道为什么第一个 SQL 语句不起作用,因为据我所知,它应该起作用。

有什么想法吗?这真的让我大吃一惊。

编辑 - 更多信息:not_sec 字段类型为 int(11)not_flgpublicar 字段类型为 char(1 )。引擎是 MySQL v. 5.6.41。表结构有50多个字段,所以我在这里犹豫不决。

编辑 2 - 更多的陌生感。当我尝试查找未发布的故事(not_flgpublicar 等于“N”)时,它起作用了:

mysql> SELECT count(*) as numStories 
FROM noticia
WHERE not_flgpublicar = 'N' AND not_sec = 1;
+------------+
| numStories |
+------------+
| 12 |
+------------+
1 row in set (0.00 sec)

但如果我试图找到已发布的,它仍然不起作用:

mysql> SELECT count(*) as numStories 
FROM noticia
WHERE not_flgpublicar = 'S' AND not_sec = 1;
+------------+
| numStories |
+------------+
| 0 |
+------------+
1 row in set (0.02 sec)

我什至试过 LIKE:

mysql> SELECT count(*) as numStories 
FROM noticia
WHERE not_flgpublicar LIKE 'S' AND not_sec = 1;
+------------+
| numStories |
+------------+
| 0 |
+------------+
1 row in set (0.02 sec)

但是,如果我这样做:

mysql> SELECT count(*) as numStories 
FROM noticia
WHERE not_flgpublicar LIKE '%S' AND not_sec = 1;
+------------+
| numStories |
+------------+
| 20151 |
+------------+
1 row in set (0.02 sec)

...有效。

not_flgpublicar 字段是 char(1),因此该字段中不能有多个字符(我检查过)。所有字段的排序规则都是 utf8mb4_unicode_ci

最佳答案

哇,看起来这实际上可能是一个 MySQL 错误。看这里:

https://bugs.mysql.com/bug.php?id=81031

在您的 SQL 语句之前尝试以下操作以验证:

SET SESSION optimizer_switch="index_merge_intersection=off";

关于mysql - SQL COUNT 没有给我正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52208484/

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