SQL 语句包含 "IN" 子句时的数据库索引

Database Index when SQL statement includes "IN" clause

我有 SQL 语句执行起来确实需要很多时间,我真的不得不以某种方式改进它。

select * from table where ID=1 and GROUP in
(select group from groupteam where 
department= 'marketing' )

我的问题是我是否应该在 ID 和 GROUP 列上创建索引会有帮助吗? 或者,如果不是,我应该在 DEPARTMENT 列的第二个 table 上创建索引吗? 或者我应该为 tables?

创建两个索引

第一个 table 有 249003。 第二个 table 总共有 900 行,而 table returns 只有 2 行。 这就是为什么我对响应如此缓慢感到惊讶。

谢谢

改为尝试联接:

select * from table t
JOIN groupteam gt
ON d.group = gt.group
where ID=1 AND gt.department= 'marketing' 

索引 table groupid 列以及 table groupteam group 列也有帮助。

您也可以使用 EXISTS,具体取决于您的数据库,如下所示:

select * from table t
where id = 1
and exists (
    select 1 from groupteam
    where   department = 'marketing'
        and group = t.group
)
  • 在 groupteam 的部门和组的各个索引上创建复合索引
  • 在 table 的 id 和 group
  • 上创建复合索引或单独索引

根据您的数据库执行 explain/analyze 以检查您的数据库引擎如何使用索引。