用了tp5和tp6在数据量上来的时候发现有些查询很慢
数据表的索引也都正常,通过打印真实sql发现比正常sql多了limit 1
下面是thinkphp框架生成的sql
SELECT
COUNT( * ) AS think_count
FROM
`edu_member`
WHERE
`school_id` = 20
AND `status` = 1
LIMIT 1
用expain分析带有limit的用到的索引和不带limit的用到的索引不一样
扫描行数也大大增加
解决思路:
既然框架无故加了limit,我们只需把无故加的limit删除即可
tp6:经排查发现在\vendor\topthink\think-orm\src\db\builder\Mysql.php的第99行是这样写的
/**
* 生成查询SQL
* @access public
* @param Query $query 查询对象
* @param bool $one 是否仅获取一个记录
* @return string
*/
public function select(Query $query, bool $one = false): string
{
$options = $query->getOptions();
return str_replace(
['%TABLE%', '%PARTITION%', '%DISTINCT%', '%EXTRA%', '%FIELD%', '%JOIN%', '%WHERE%', '%GROUP%', '%HAVING%', '%ORDER%', '%LIMIT%', '%UNION%', '%LOCK%', '%COMMENT%', '%FORCE%'],
[
$this->parseTable($query, $options['table']),
$this->parsePartition($query, $options['partition']),
$this->parseDistinct($query, $options['distinct']),
$this->parseExtra($query, $options['extra']),
$this->parseField($query, $options['field'] ?? '*'),
$this->parseJoin($query, $options['join']),
$this->parseWhere($query, $options['where']),
$this->parseGroup($query, $options['group']),
$this->parseHaving($query, $options['having']),
$this->parseOrder($query, $options['order']),
$this->parseLimit($query, $one ? '1' : $options['limit']),//这里的1改成空字符串即可
$this->parseUnion($query, $options['union']),
$this->parseLock($query, $options['lock']),
$this->parseComment($query, $options['comment']),
$this->parseForce($query, $options['force']),
],
$this->selectSql
);
}
把1改成空字符串,再打印sql就很干净了