假设我有两个表:
table1(ID, attribute1, attribute2)
和
table2(ID, attribute1, attribute2)
ID是两张表的主键
我有一个观点:
create view myview as
select ID, attribute1, attribute2 from table1
union
select ID, attribute1, attribute2 from table1
当我执行如下查询时,我可以利用主键索引的优势吗(在一般的 sql 中,在我的例子中是 mysql)?
select * from myview where ID = 100
最佳答案
这取决于您的查询。使用 View 可能会限制可以有效使用的索引。
例如,使用我手边的一个表,我可以使用 2 个 UNIONed 选择创建一个 View ,每个选择都带有一个 WHERE 子句。
CREATE VIEW fred AS
SELECT *
FROM item
WHERE code LIKE 'a%'
UNION SELECT *
FROM item
WHERE mmg_code LIKE '01%'
code 和 mmg_code 字段都有索引。该表也有 id 作为主键(最高值约为 59500)。
作为查询,我可以从 View 中选择,或者执行与 View 类似的查询,或者我可以使用 OR(所有 3 个都应该给出相同的结果)。我得到 3 个完全不同的解释:-
SELECT *
FROM item
WHERE id > 59000
AND code LIKE 'a%'
UNION SELECT *
FROM item
WHERE id > 59000
AND mmg_code LIKE '01%';
给出并解释
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY item range PRIMARY,code,id,id_mmg_code,id_code,code_id PRIMARY 4 NULL 508 Using where
2 UNION item range PRIMARY,id,mmg_code,id_mmg_code,id_code,mmg_code_id PRIMARY 4 NULL 508 Using where
NULL UNION RESULT <union1,2> ALL NULL NULL NULL NULL NULL Using temporary
而下面
SELECT *
FROM item
WHERE id > 59000
AND (code LIKE 'a%'
OR mmg_code LIKE '01%');
给出并解释
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE item range PRIMARY,code,id,mmg_code,id_mmg_code,id_code,code_id,mmg_code_id PRIMARY 4 NULL 508 Using where
及以下内容
SELECT *
FROM fred
WHERE id > 59000;
给出并解释
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY <derived2> ALL NULL NULL NULL NULL 4684 Using where
2 DERIVED item range code,code_id code 34 NULL 1175 Using index condition
3 UNION item range mmg_code,mmg_code_id mmg_code 27 NULL 3509 Using index condition
NULL UNION RESULT <union2,3> ALL NULL NULL NULL NULL NULL Using temporary
正如您所看到的,因为在 View 中使用了索引,它影响了从 View 中选择时可以使用的索引。
最好的索引可能是主键,但 View 不使用它。
关于mysql - 索引是否与 View 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37431849/