建立索引和創建視圖(結合YGGL.sql)


.請按要求對YGGL庫建立相關索引

1)使用create index 語句創建索引

1.employees表中的員工部門號創建普通索引depart_ind.

mysql> create index depart_ind

    -> on employees(員工編號);

Query OK, 12 rows affected (0.04 sec)

Records: 12  Duplicates: 0  Warnings: 0

 

2.對 employees表中的姓名和地址創建復合索引 ad_ind.

mysql> create  index ad_ind  on employees(姓名,地址);

Query OK, 12 rows affected (0.00 sec)

Records: 12  Duplicates: 0  Warnings: 0

 

3. departments表中的部門名稱創建唯一索引.

mysql> create  unique index department_index   

    -> on departments(部門名稱);

Query OK, 5 rows affected (0.04 sec)

Records: 5  Duplicates: 0  Warnings: 0

 

(2) 使用alter table 語句添加索引

1.employees表中的出生日期添加一個唯一索引date_ind,姓名和性別添加一個復合索引na_ind.

mysql> alter table employees add unique index date_ind(出生日期),

    -> add  index na_ind(姓名,性別);

Query OK, 12 rows affected (0.03 sec)

Records: 12  Duplicates: 0  Warnings: 0

 

2. departments 表中的部門編號創建主鍵索引.

mysql> alter table departments

    -> add  primary key 部門編號_index(部門編號);

Query OK, 5 rows affected (0.00 sec)

Records: 5  Duplicates: 0  Warnings: 0

 

(3) 創建表的同時創建索引

創建表cpk(產品編號,產品名稱,單價,庫存量),並對產品編號創建主鍵,在庫存量和單價上創建復合索引cpk_fh.

mysql> create table cpk(

    -> 產品編號 char(20)not null ,產品名稱 varchar(30),單價 decimal(10,2),庫存量 int(10),

    -> primary key (產品編號),

    -> index cpk_fh(庫存量,單價));

Query OK, 0 rows affected (0.03 sec)

.顯示employees表的索引情況

.刪除索引

1)使用drop 方式刪除索引

1.刪除employees表中的員工部門號的索引

mysql> drop index depart_index on employees;

Query OK, 12 rows affected (0.00 sec)

Records: 12  Duplicates: 0  Warnings: 0

 

2)使用alter 方式刪除索引

2.刪除employees表中姓名和性別的復合索引na_ind

mysql> drop index na_ind on employees;

Query OK, 12 rows affected (0.00 sec)

Records: 12  Duplicates: 0  Warnings: 0

 

四、簡述索引的優缺點

優:(1)通過創建唯一性索引,可以保證數據記錄的唯一性。

2)可以大大加快數據的檢索速度。

3) 可以加快表與表之間的連接,這一點在實現數據的參照完整性方面有特別的意義。

4)在使用ORDEY BY 和GROUP BY子句進行數據檢索時,可以顯著減少查詢中分組和排序的時間。

5)使用索引可以在檢索數據的過程中使用優化隱藏器,提高系統性能。

:檢索引帶來的查找速度的提高也是有代價的,因為索引要占用存儲空間,而且為了維護索引的有效性,向表中插入數據或者更新數據時,數據庫還要執行額外的操作來維護索引

 

五、創建視圖

1.創建視圖emp_view,包含所有男員工的員工編號,姓名,工作年限和學歷.

mysql> create or replace view emp_view

    -> as

    -> select 員工編號,姓名,工作年限,學歷

    -> from employees

    -> where 性別=1;

Query OK, 0 rows affected (0.00 sec)

 

2.emp_view視圖中查詢工作年限在兩年以上的員工信息。

mysql> select * from emp_view

    -> where 工作年限>2;

+--------------+-----------+--------------+--------+

| 員工編號     | 姓名      | 工作年限     | 學歷   |

+--------------+-----------+--------------+--------+

| 000001       | 王林      |            8 | 大專   |

| 010008       | 伍容華    |            3 | 本科   |

| 102201       | 劉明      |            3 | 本科   |

| 302566       | 李玉珉    |            3 | 本科   |

+--------------+-----------+--------------+--------+

4 rows in set (0.00 sec)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM