gpt4 book ai didi

mysql - 如何优化 'IN' 查询?

转载 作者:行者123 更新时间:2023-11-29 07:13:40 25 4
gpt4 key购买 nike

**** 编辑 ****

14 毫秒可能看起来不多,但是正如您在下面的“PostgresSQL 说明”中看到的,PostgreSQL 正在对 80,000 行进行顺序扫描。必须有一种方法来避免这种扫描并进行几次索引查找。

**** 编辑结束 ****

我正在尝试无模式的想法,我有以下三个表:

表格中填充了 100,000 个随机条目。

entities(_primary_key SERIAL PRIMARY KEY, _id CHAR(32) UNIQUE, 
data BYTEA)

index_username_profile_names(_id CHARE(32) PRIMARY KEY,
key VARCHAR UNIQUE)

index_username_email(_id CHAR(32) PRIMARY KEY, key VARCHAR)

index_username_email(key) 上使用非唯一索引

我的 SQL 查询是:

SELECT data FROM entities WHERE 
_id IN (SELECT _id FROM index_users_email WHERE key = 'test')
OR
_id in (SELECT _id FROM index_users_profile_name WHERE key = 'test')

尽管“测试”在任何一个“索引”表中都不存在,但无论我使用 PostgreSQL 还是 MySQL,这都花费了 14 毫秒,所以这一定是我做错了。

知道如何优化它,或者我做错了什么?

谢谢!

Postgres 解释:

Seq Scan on entities  (cost=16.88..4776.15 rows=80414 width=163) (actual time=15.169..15.169 rows=0 loops=1)
Filter: ((hashed SubPlan 1) OR (hashed SubPlan 2))
Rows Removed by Filter: 107218
SubPlan 1
-> Index Scan using index_users_email_key_idx1 on index_users_email (cost=0.42..8.44 rows=1 width=33) (actual time=0.039..0.039 rows=0 loops=1)
Index Cond: ((key)::text = 'test'::text)
SubPlan 2
-> Index Scan using index_users_profile_name_key_idx1 on index_users_profile_name (cost=0.42..8.44 rows=1 width=33) (actual time=0.071..0.071 rows=0 loops=1)
Index Cond: ((key)::text = 'test'::text)
Planning time: 0.202 ms
Execution time: 15.216 ms

最佳答案

ORed(连接)条件通常不好,请尝试使用UNION:

SELECT data FROM entities 
WHERE _id IN
( SELECT _id
FROM index_users_email
WHERE key = 'test'
)
UNION
SELECT data FROM entities
WHERE _id in
( SELECT _id
FROM index_users_profile_name
WHERE key = 'test'
)

关于mysql - 如何优化 'IN' 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38722050/

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