这个查询有很多不同的东西:
SELECT st.id AS stid,
st.category,
st.maxsubscriptions,
CONCAT (
st.category,
' (',
COUNT(CASE
WHEN gs.id_subtournament = st.id
THEN 1
ELSE NULL
END),
'/',
st.maxsubscriptions,
')'
) AS ststring
FROM de_subtournaments AS st
LEFT JOIN de_gamers AS gs ON st.id = gs.id_subtournament
WHERE st.type = 0
AND st.id_tournament = '6'
GROUP BY st.id
此查询的索引应该是什么样的?为什么?
答案 0 :(得分:1)
以下是我建议维护的索引:
`de_subtournaments`: `id`, unless it's the primary key already with an index
`de_subtournaments`: `type` + `id_tournament`
`de_gamers`: `id_subtournament`, unless the foreign key already has an index
如果您有其他查询需要针对de_subtournaments
针对id_tournament
运行而不关心type
,请考虑同时创建以下索引(如果它尚未存在)对于外键):
`de_subtournaments`: `id_tournament`
答案 1 :(得分:0)
这是一个查询提法问题,而不仅仅是索引问题。
请注意您拥有JOIN
和GROUP BY
的方式。我称之为" inflate-deflate"图案。它可能很昂贵。
加速此类查询的诀窍是摆脱GROUP BY
并将JOIN
转换为子查询。
SELECT st.id AS stid, st.category, st.maxsubscriptions,
CONCAT ( st.category,
' (',
IFNULL(
( SELECT COUNT(*)
FROM de_gamers
WHERE id_subtournament = st.id ),
0),
'/',
st.maxsubscriptions,
')'
) AS ststring
FROM de_subtournaments AS st
WHERE st.type = 0
AND st.id_tournament = '6'
现在,要重新检查索引:
st: INDEX(type, id_tournament) -- in either order
de_gamers: (id_subtournament)