正确优化PHP Mysqli查询

时间:2015-07-08 17:15:37

标签: php mysql mysqli

我最近在INNER JOIN编码方面提供了一些帮助,以帮助优化我所拥有的慢速脚本。在优化剩余代码并对其进行测试之后,我现在能够确定下面的查询是否会减慢脚本速度。

任何人都可以帮我优化下面的代码,以加快查询速度。索引很好,我认为代码现在已经过时了。

        $cqry = "SELECT * FROM ftree_node WHERE id IN ";
        if($wrow['A'] == 'F') {
            $cqry .= '(SELECT DISTINCT t1.relation_from FROM ftree_tree_node_relation AS t1, ftree_tree_node_relation AS t2 WHERE ';
            $cqry .= '(t1.relation_from=t2.relation_from) AND (t1.relation_type <> t2.relation_type) AND ';
            $cqry .= '(t1.relation_to ='.$treeDB->real_escape_string($rrow[id]).' AND t1.relation_type="'.$treeDB->real_escape_string($FAT).'") AND (t2.relation_to = '.$treeDB->real_escape_string($wrow[id]).' AND t2.relation_type = "'.$treeDB->real_escape_string($MOT).'"))';
        } else {
            $cqry .= '(SELECT DISTINCT t1.relation_from FROM ftree_tree_node_relation AS t1, ftree_tree_node_relation AS t2 WHERE ';
            $cqry .= '(t1.relation_from=t2.relation_from) AND (t1.relation_type <> t2.relation_type) AND ';
            $cqry .= '(t1.relation_to = '.$treeDB->real_escape_string($rrow[id]).' AND t1.relation_type="'.$treeDB->real_escape_string($MOT).'") AND (t2.relation_to = '.$treeDB->real_escape_string($wrow[id]).' AND t2.relation_type = "'.$treeDB->real_escape_string($FAT).'"))';
        }
        $cres = $treeDB->query($cqry);

谢谢大家。

1 个答案:

答案 0 :(得分:0)

尝试摆脱子选择:

示例:

SELECT fn.* 
FROM ftree_node fn
    INNER JOIN ftree_tree_node_relation ftnr1 ON ftnr1.relation_from = fn.id
    INNER JOIN ftree_tree_node_relation ftnr2 ON ftnr2.relation_from = fn.id
WHERE
    ftnr1.relation_type <> ftnr2.relation_type
    AND (ftnr1.relation_to = ????
        AND t1.relation_type= ????
        AND (
            ftnr2.relation_to = ????
                    AND ftnr2.relation_type = ????
        )
    )

然后,如果仍然很慢,请用EXPLAIN EXTENDED分析它,看看索引是否正确使用。

注意:上面的查询未经过测试,可用于指示。为了更好的可读性,我使用????删除了值。