mysqli选择导致错误500内部错误

时间:2014-10-30 21:33:39

标签: php mysql mysqli fetch

我已经通过其他类似标题的问题,但无法弄清楚我的代码有什么问题:|

所以这里是简单的mysql代码:

SELECT COUNT(id) AS sum FROM series WHERE id IN (SELECT s_id FROM s_genre WHERE g_id IN (1,5,19) GROUP BY s_id HAVING COUNT(s_id)>=3) AND stype=0 LIMIT 1

好吧,如果我们根据系列类型进行搜索,它会用来计算返回的列数。内部代码将在不到一秒的时间内返回183条记录,但是当我运行整个代码时,它会在大约一分钟后返回内部错误500。此 系列 表包含约5000条记录。 s_genre 表包含大约25000条记录。那么您认为问题是什么? 在此先感谢:)

1 个答案:

答案 0 :(得分:1)

这是您的查询:

SELECT COUNT(id) AS sum
FROM series
WHERE id IN (SELECT s_id
             FROM s_genre
             WHERE g_id IN (1, 5, 19)
             GROUP BY s_id
             HAVING COUNT(s_id) >= 3
            ) AND
      stype = 0
LIMIT 1;

尝试将其重新措辞为join。这些通常会更有效地进行优化:

SELECT COUNT(s.id) AS sum
FROM series s JOIN
     (SELECT s_id
      FROM s_genre
      WHERE g_id IN (1, 5, 19)
      GROUP BY s_id
      HAVING COUNT(s_id) >= 3
     ) g
     on s.id = g.s_id
WHERE stype = 0;

注意,limit不执行任何操作,因为没有group by的聚合查询只返回一行。

如果上述内容无法提高效果,请在s_genre(s_id, g_id)上创建索引并使用exists编写查询:

select count(s.id)
from series s
where s.stype = 0 and
      exists (select 1 from s_genre g where s.id = g.sid and g.g_id = 1) AND
      exists (select 1 from s_genre g where s.id = g.sid and g.g_id = 5) AND
      exists (select 1 from s_genre g where s.id = g.sid and g.g_id = 19);