我有2個表postsTable和groupsTable。我在下面發布了兩者的結構和索引。
我的問題是,在下面的查詢中,mysql 應該使用groupsTable 的“index nCode”。但它完全忽略了它,即使它把它列為一個可能的索引。
postTable 的索引按預期進行。
我可以在這里做些什么來解決這個問題?謝謝
create table postsTable
(pid int(18) auto_increment not null primary key,
userID int(10),
stat int(10),
mainID int(10),
title varchar(256),
INDEX( userID, stat, mainID )
);
create index postPStat on postsTable (stat, mainID);
create table groupsTable
(cid int(10) auto_increment not null primary key,
nCode int(10),
cStat (char2) default 'y',
aCode varchar(256),
groupName varchar(256),
INDEX(nCode, cStat, aCode )
);
查詢是這樣的:
select p.pid, p.title, t.groupName
from postsTable as p
left join groupsTable as t
on p.stat = t.nCode
where
p.stat = t.nCode
and p.mainID=0
and t.cStat='y'
group by p.pid
解釋一下是這樣的:
2 in array
Array
(
[0] => Array
(
[id] => 1
[select_type] => SIMPLE
[table] => t
[partitions] =>
[type] => system
[possible_keys] => nCode
[key] =>
[key_len] =>
[ref] =>
[rows] => 1
[filtered] => 100.00
[Extra] => Using filesort
)
[1] => Array
(
[id] => 1
[select_type] => SIMPLE
[table] => p
[partitions] =>
[type] => ref
[possible_keys] => PRIMARY,id,id_2,postPStat
[key] => postPStat
[key_len] => 16
[ref] => const,const
[rows] => 1
[filtered] => 100.00
[Extra] => Using index condition
)
)
uj5u.com熱心網友回復:
您當前的查詢似乎不需要GROUP BY,而且連接邏輯很可能有問題。考慮這個版本:
SELECT p.pid, p.title, t.groupName
FROM postsTable p
LEFT JOIN groupsTable t
ON p.stat = t.nCode AND
t.cStat = 'y'
WHERE p.mainID = 0;
您想要的索引位于groupsTable:
CREATE INDEX idx ON groupsTable(nCode, cStat, groupName);
請注意,此索引與 不同(nCode, cStat, aCode),后者是您當前擁有的索引。您的索引不涵蓋 select 子句,因此不涵蓋整個查詢。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/349055.html
標籤:mysql
