Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/269.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.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
Php 如何修复慢速sql查询_Php_Mysql_Sql - Fatal编程技术网

Php 如何修复慢速sql查询

Php 如何修复慢速sql查询,php,mysql,sql,Php,Mysql,Sql,我在做一个可湿性粉剂留言簿,我在某个地方犯了一个错误。起初,我尝试使用join,但由于所有这些条件,无法使其正常工作,因此我写了以下内容: $query = " (select *, (select count(cid) from ctable WHERE nid = vid) as posts, (select timestamp from ctable where nid = vid order by timestamp desc limi

我在做一个可湿性粉剂留言簿,我在某个地方犯了一个错误。起初,我尝试使用join,但由于所有这些条件,无法使其正常工作,因此我写了以下内容:

$query = "  
        (select *,
        (select count(cid) from ctable WHERE nid = vid) as posts,
        (select timestamp from ctable where nid = vid order by timestamp desc limit 1) as lt,
        (select count(vid) from ntable) as total
        FROM ntable
        )";

它做的正是它想要做的,但速度非常慢。我知道我喊着使用join,但我想不出来。

根据我的经验水平。尝试使用nolock,因为我更新了你的查询

$query = '(select *,
        (select count(cid) from ctable with(nolock) WHERE nid = vid) as posts,
        (select timestamp from ctable with(nolock) where nid = vid order by timestamp desc limit 1) as lt,
        (select count(vid) from ntable with(nolock)) as total
        FROM ntable with(nolock)
        )';

您正在使用Order by for with timestamp列,而不是使用
getdate()-1
(意味着旧数据的天数计数,以便查询将提高其性能。)

连接查询可能是这样的(很难确定,因为您没有提供表定义)


但是假设你有nid和vid的索引,我怀疑你是否会看到改进——我很想知道

没有。问题不在于获取数据的速度是否足够快,问题在于数据显示的顺序(lt)。这需要最长的时间

返回错误。它不喜欢有(无锁)部分。
select *,p.posts,t.ts,(select count(*) from ntable) total 
 from ntable
 join (select vid,count(*) posts from ctable group by vid) p on p.nid = vid
 join (select vid,max(timestamp) ts from ctable group by vid) t on t.nid = vid