视图与索引以及表的区别[以Mysql为例]

视图与索引,以及表的区别[以Mysql为例]

1.概念

1.视图

  • 01.是基于 SQL 语句的结果集的可视化的表。
  • 02.视图包含行和列,就像一个真实的表。视图中的字段就是来自一个或多个数据库中的真实的表中的字段。
  • 03.视图是逻辑概念,并非真实存在。
  • 04.是一个SQL集,它表示的是对一个SQL查询的结果,它不同于一张物理表,它是一个逻辑表。

2.索引:

  • 1.在不读取整个表的情况下,索引使数据库应用程序可以更快地查找数据。[ 是为了快速查询而针对某些字段建立起来的。]
  • 2.更新一个包含索引的表需要比更新一个没有索引的表更多的时间,这是由于索引本身也需要更新。

3.表

  • 01.数据库中的数据都是存储在表中的
  • 02.表是物理存储的,真实存在的
2.案例

创建索引:create index degree_fast on score (degree);
这里的dgeree_fast是索引名,score是表明,degree是表中的一个字段。
创建视图:

create view [viewName] as 
select [someFields]
from [tableName]

删除索引:
- 01.方式一:drop index degree_fast on score;
- 02.方式二:alter table score drop index degree_fast;

mysql>  drop index index1 on score;
ERROR 1553 (HY000): Cannot drop index 'index1': needed in a foreign key constraint


mysql> show create table score\G;
*************************** 1. row ***************************
       Table: score
Create Table: CREATE TABLE `score` (
  `sno` varchar(20) NOT NULL,
  `cno` varchar(20) NOT NULL,
  `degree` decimal(4,1) DEFAULT NULL,
  KEY `cno_inScore` (`cno`),
  KEY `index1` (`sno`,`cno`),
  CONSTRAINT `cno_inScore` FOREIGN KEY (`cno`) REFERENCES `course` (`cno`),
  CONSTRAINT `sno_inScore` FOREIGN KEY (`sno`) REFERENCES `student` (`sno`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

ERROR:
No query specified

mysql> alter table score drop foreign key cno_inScore;
Query OK, 0 rows affected (0.08 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> alter table score drop foreign key sno_inScore;
Query OK, 0 rows affected (0.06 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql>  drop index index1 on score;
Query OK, 0 rows affected (0.11 sec)
Records: 0  Duplicates: 0  Warnings: 0

Mysql cannot drop index needed in a foreign key constraint.Mysql不能在外键约束下删除索引。如果有外键的话,需要先把外键删除,然后再删除索引。

删除视图:drop view myview

猜你喜欢

转载自blog.csdn.net/liu16659/article/details/80649394