Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 向查询中添加计数会导致查询卡住_Mysql_Sql - Fatal编程技术网

Mysql 向查询中添加计数会导致查询卡住

Mysql 向查询中添加计数会导致查询卡住,mysql,sql,Mysql,Sql,编辑:将其简化为最简单的示例: select COUNT(*) from a_table use index(contract) left join b_table on a_table.contract = b_table.contract 还有,没什么解释: 我有两个几乎相同的查询(b_table是一个临时表): 此查询在0.25秒内可靠返回。以下是解释: 这里是相同的查询,仅在if的周围有一个COUNT(): select COUNT(IF (b.contract IS NULL,

编辑:将其简化为最简单的示例:

select COUNT(*)
from a_table use index(contract)
left join b_table on a_table.contract = b_table.contract
还有,没什么<代码>解释:

我有两个几乎相同的查询(
b_table
是一个临时表):

此查询在0.25秒内可靠返回。以下是
解释

这里是相同的查询,仅在
if
周围有一个
COUNT()

select COUNT(IF (b.contract IS NULL, 1, NULL)) c
from a_table a
left join (select contract from b_table) b on a.contract = b.contract
这张照片显示的是“发送数据”,至少在几分钟后,似乎挂断了,我什么也没得到。以下是
解释

(注意
d
=
a_表a
eric_-tmp
=
b_表
。希望不要太混乱。)

这是导致混乱的原始查询,上面的代码试图重写它:

select count(*) from a_table a
where not exists (select 1 from b_table b where a.contract = b.contract)

当然也挂了。这到底是怎么回事?我尝试过添加和使用非唯一索引,但似乎也没有帮助。我不明白为什么<代码>计数>代码会在这里引起一个问题。

您可能会考虑当返回第一行而不是最后一行时所做的第一个查询。第二个查询需要遍历所有数据,然后才能返回任何内容

子查询(MySQL称之为“派生表”)会影响性能。消极的

您的
不存在
查询非常合理:

select count(*)
from a_table a
where not exists (select 1 from b_table b where a.contract = b.contract);

为了提高性能,您需要在
b_表(合同)
上建立索引。这可能会解决您的性能问题,除非表太大。

@GordonLinoff-对此很抱歉。更改sum的计数:sum(如果(b.contract为NULL,1,0))c和testAre您是否使用InnoDB或MyISAM引擎?@ImreL-它们都是InnoDB。两个表上的字段
contract
的数据类型是什么?在
b_表上有一个索引。contract
。我同意这个查询看起来很好,但它仍然存在,而且永远不会返回任何东西(至少只要我愿意等待,大约500万次)。此外,我们讨论的是每行35-45k行。不是很大。@JaredFarrish。使用索引,此查询应在几秒钟或几十秒钟内完成。您确定表b上有索引,其中
contract
是索引中的第一个键吗?是。你可以在解释中看到。@JaredFarrish。您应该修复查询,以便解释中的表名与查询中的表名匹配。
select count(*)
from a_table a
where not exists (select 1 from b_table b where a.contract = b.contract);