1. 程式人生 > >mysql 索引查詢 、建立 create index 與 add index 的區別

mysql 索引查詢 、建立 create index 與 add index 的區別

1、索引查詢

------TABLE_SCHEMA  庫名;TABLE  表名

------AND UPPER(INDEX_NAME) != 'PRIMARY'  只查詢索引,不需要主鍵

SELECT
CONCAT('ALTER TABLE `',TABLE_NAME,'` ', 'ADD ',
IF(NON_UNIQUE = 1,
CASE UPPER(INDEX_TYPE)
WHEN 'FULLTEXT' THEN 'FULLTEXT INDEX'
WHEN 'SPATIAL' THEN 'SPATIAL INDEX'
ELSE CONCAT('INDEX `',
INDEX_NAME,
'` USING ',
INDEX_TYPE
)
END,
IF(UPPER(INDEX_NAME) = 'PRIMARY',
CONCAT('PRIMARY KEY USING ',
INDEX_TYPE
),
CONCAT('UNIQUE INDEX `',
INDEX_NAME,
'` USING ',
INDEX_TYPE
)
)
),'(', GROUP_CONCAT(DISTINCT CONCAT('`', COLUMN_NAME, '`') ORDER BY SEQ_IN_INDEX ASC SEPARATOR ', '), ');') AS 'Show_Add_Indexes'
FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = 'test'  and TABLE ='test_table'
AND UPPER(INDEX_NAME) != 'PRIMARY'
GROUP BY TABLE_NAME, INDEX_NAME
ORDER BY TABLE_NAME ASC, INDEX_NAME ASC;

 2、索引刪除

alter table table_name drop index index_name;

3、建立索引

alter table table_name add index_name using btree('column_name',...,'column_name');

create unique index index_name on table_name('column_name');

兩者區別:

(1)add index_name 支援一次多個索引建立alter table table_name add index_name using btree('column_name',...,'column_name'),add index_name using btree('column_name',...,'column_name')

(2)add index_name 可以建立 PRIMARY KEY

(3)create  index 建立時必須制定index_name,alter 可以使用預設名