php – 优化此SQL查询

前端之家收集整理的这篇文章主要介绍了php – 优化此SQL查询前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

这个SQL查询让我感到厌恶.我没有写它,但它是我们服务器问题的一个重要原因.我愿意将它分成多个查询并通过PHP进行一些处理(比如,RAND()).

$sql = "SELECT a.code,a.ad_id,a.position,a.type,a.image,a.url,a.height,a.width
    FROM " . AD_TABLE ." a," . USER_GROUP_TABLE . " g
    WHERE (a.max_views >= a.views OR a.max_views = '0')
    AND (FIND_IN_SET(" .$forum_id. ",a.show_forums) > 0 OR a.show_all_forums = '1')
    AND g.user_id = " . $user->data['user_id'] . "
    AND FIND_IN_SET(g.group_id,a.groups)
    AND FIND_IN_SET(" . $user->data['user_rank'] . ",a.ranks)
    AND a.start_time < " . time() . "
    AND a.end_time > " . time() . "
    AND (a.clicks <= a.max_clicks OR a.max_clicks = '0')
    ORDER BY rand()";

是的,粘贴之后我觉得很蠢…

编辑:以下是上述格式的示例查询“EXPLAIN”的结果,逗号分隔:

"id","select_type","table","type","possible_keys","key","key_len","ref","rows","Extra"
1,"SIMPLE","g","user_id","3","const",6,"Using temporary; Using filesort"
1,"a","ALL","max_views","",10,"Using where"

它是

最佳答案
你有三个主要问题:

> FIND_IN_SET.

这不是一件容易的事,一个索引不能让它变得更快.创建多对多关系表(或多个表).

> a.start_time< GETDATE()和a.end_time> GETDATE()

MysqL不善于优化.您可以将时间跨度作为几何框保留,并为它们创建一个空间索引,这将更快(尽管可读性较差)

>兰德令()

如果您使用它来对数据进行采样(即,您不需要所有行,而是需要一个小的随机子集),那么有一种更有效的方法可以执行此操作,如本文在我的博客中所述:

> Selecting random rows

原文链接:https://www.f2er.com/mysql/433544.html

猜你在找的MySQL相关文章