【问题标题】:Covering index in MySQL for join + where queries覆盖 MySQL 中的索引以进行 join + where 查询
【发布时间】:2017-06-22 15:03:57
【问题描述】:
假设我的查询是:
SELECT adstable.adid FROM `adstable`
inner join userstable on
(adstable.adid = userstable.adid)
WHERE adstable.desktopimp > 100
and adstable.mobileimp > 100
and adstable.userbal > 0.02
and adstable.realbal> 0.02
order by adstable.imptotal asc
我应该索引哪些列,以确保此查询的“覆盖索引”?
【问题讨论】:
标签:
mysql
indexing
query-optimization
mariadb
【解决方案1】:
每个“广告”可以有多个“用户”吗?能有零吗?如果两者都不是,那么
SELECT a.adid
FROM `adstable` AS a
WHERE a.desktopimp > 100
and a.mobileimp > 100
and a.userbal > 0.02
and a.realbal> 0.02
AND EXISTS (
SELECT *
FROM userstable
WHERE adid = a.adid
)
order by a.imptotal asc
这是否是一个更好的公式,有这些指标:
userstable: INDEX(adid)
adstable: INDEX(imptotal) -- in case it is better to avoid the sort
INDEX(desktopimp) -- in case it is most selective
INDEX(mobileimp)
INDEX(userbal)
INDEX(realbal)
“覆盖”索引将包括查询中使用的 adstable 的所有 6 列。这相当笨重,用途也很可疑。
请提供SHOW CREATE TABLE——查看数据类型、引擎等可能会有所帮助。
在构建最佳索引时,从与= 比较的任何列开始。如果这处理了所有的WHERE,那么转到ORDER BY 列。你没有这种情况,因为你没有使用=。