gpt4 book ai didi

MySQL Select Slow 因为 Order By

转载 作者:行者123 更新时间:2023-11-28 23:31:20 25 4
gpt4 key购买 nike

我有以下选择:

SELECT a.userid,
(SELECT name FROM photos WHERE userid=a.userid AND type='profile' LIMIT 1) AS photo,
(SELECT attractive FROM photos WHERE userid=a.userid AND type='profile' LIMIT 1) AS attractive,
IF(a.domain="domanin.com",1,2) AS preferredDomain,
IF(a.domain LIKE "%domain.com",1,2) AS preferredSubDomain
FROM users AS a
WHERE a.gender = 1
AND a.visible = 1
AND a.active = 1
AND a.completed = 1
AND a.approved = 1
HAVING photo IS NOT NULL
ORDER BY preferredDomain ASC,
attractive DESC,
a.lastlogin DESC,
preferredSubDomain ASC
LIMIT 100;

这需要 5-6 秒才能运行。

如果我删除 Order By,运行需要 0.23 秒。

我假设这是因为 SELECT 必须生成内部 SELECTS 才能进行排序?这是正确的吗?用户表有 60,000 个条目。

谁能就如何更好地构造此查询提供一些建议?

最佳答案

尝试使用连接而不是嵌套查询,例如:

SELECT 
a.userid,
p.name,
p.attractive,
IF(a.domain="domain.com",1,2) AS preferredDomain,
IF(a.domain LIKE "%domain.com",1,2) AS preferredSubDomain
FROM users AS a
JOIN photos AS p ON (p.userid = a.userid AND p.type = 'profile')
WHERE
a.gender = 1
AND a.visible = 1
AND a.active = 1
AND a.completed = 1
AND a.approved = 1
HAVING photo IS NOT NULL
ORDER BY preferredDomain ASC, attractive DESC, a.lastlogin DESC, preferredSubDomain ASC
LIMIT 100;

有关连接语法的文档可在此处找到: http://dev.mysql.com/doc/refman/5.7/en/join.html

关于MySQL Select Slow 因为 Order By,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37221976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com