我有一个 mysql sql select 需要很长时间才能返回数据。
表
╔════════════════╗ ╔════════════════╗
║ ITEM ║ ║ Workspace ║
╠════════════════║ ╠════════════════║
║ id ║ ║ id ║
║ guid ║ ║ guid ║
║ workspace_id ║ ║ company_id ║
║ deleted ║ ║ deleted ║
╚════════════════╝ ╚════════════════╝
Indexes: id, guid Indexes: id, guid,
workspace_id company_id
╔════════════════╗ ╔════════════════════╗
║ COMPANY ║ ║ item_category_xref ║
╠════════════════║ ╠════════════════════║
║ id ║ ║ item_id ║
║ deleted ║ ║ category_id ║
╚════════════════╝ ╚════════════════════╝
Indexes: id Indexes: item_id, category_id
╔════════════════╗ ╔═════════════════════╗
║ item_image ║ ║ tracking_action ║
╠════════════════║ ╠═════════════════════║
║ item_id ║ ║ id ║
║ sequence ║ ║ guid ║
╚════════════════╝ ║ action ║
Indexes: ║ context ║
(item_id, sequence) ║ deleted ║
╚═════════════════════╝
SQL
SELECT
itm.id "item.id",
ws.id "workspace.id",
co.id "company.id",
((SELECT count(*) FROM item_category_xref icx
WHERE icx.item_id = itm.id
AND icx.featured = 1) > 0) "featured",
(SELECT COUNT(*) FROM tracking_action ta1
WHERE ta1.context = 'ITEM'
AND ta1.context_guid = itm.guid
AND ta1.action = 'VIEW') ta_view_count ,
(SELECT COUNT(*) FROM tracking_action ta2
WHERE ta2.context = 'ITEM'
AND ta2.context_guid = itm.guid
AND ta2.action = 'SEARCH_RESULT') ta_search_count
FROM item itm
JOIN workspace ws
ON itm.workspace_id = ws.id
AND ws.deleted != 1
JOIN company co
ON ws.company_id = co.id
AND co.deleted != 1
JOIN item_category_xref icx
ON itm.id = icx.item_id
AND icx.category_id = 1
LEFT JOIN item_image ii
ON itm.id = ii.item_id
AND ii.sequence = 1
WHERE itm.deleted != 1
HAVING featured > 0;
解释
这个查询是我努力减少和改进的结果。我已经从需要 180 秒的原始查询到现在需要大约 20 秒的查询,但仍然不够。
谁能为此查询提供性能改进?
我们正在搜索几百万行数据,所以每一点都会有所帮助。