我有两张桌子
CREATE TABLE Categories (
Category INTEGER,
Id INTEGER,
FOREIGN KEY (Category) REFERENCES CategoriesInfo(Category)
)
CREATE TABLE 'CategoriesInfo' (
'Category' INTEGER PRIMARY KEY NOT NULL,
'Name' TEXT
)
带索引
CREATE UNIQUE INDEX idxCategory ON Categories (Category, Id)
如果我跑
EXPLAIN QUERY PLAN
SELECT CategoriesInfo.Category, Name
FROM Categories, CategoriesInfo
Where Categories.Category=CategoriesInfo.Category AND Id=:id
ORDER BY Name
它说
Array
(
[0] => Array
(
[selectid] => 0
[order] => 0
[from] => 1
[detail] => SCAN TABLE CategoriesInfo (~1475 rows)
)
[1] => Array
(
[selectid] => 0
[order] => 1
[from] => 0
[detail] => SEARCH TABLE Categories USING COVERING INDEX idxCategory (Category=? AND Id=?) (~1 rows)
)
[2] => Array
(
[selectid] => 0
[order] => 0
[from] => 0
[detail] => USE TEMP B-TREE FOR ORDER BY
)
)
但是如果我使用连接
EXPLAIN QUERY PLAN
SELECT CategoriesInfo.Category, CategoriesInfo.Name
FROM Categories
LEFT JOIN CategoriesInfo ON (Categories.Category=CategoriesInfo.Category)
WHERE Categories.Id=:id
ORDER BY Name
我明白了
Array
(
[0] => Array
(
[selectid] => 0
[order] => 0
[from] => 0
[detail] => SEARCH TABLE Categories USING AUTOMATIC COVERING INDEX (Id=?) (~6 rows)
)
[1] => Array
(
[selectid] => 0
[order] => 1
[from] => 1
[detail] => SEARCH TABLE CategoriesInfo USING INTEGER PRIMARY KEY (rowid=?) (~1 rows)
)
[2] => Array
(
[selectid] => 0
[order] => 0
[from] => 0
[detail] => USE TEMP B-TREE FOR ORDER BY
)
)
然后,使用连接应该更快。但是当我用 phpliteadmin 运行这两个代码时,
- 第一个需要 0 秒
- 第二次耗时 0.3281 秒
为什么??