MySQL导出、删除索引Index和约束的方法

1. 导出创建自增字段语句:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
SELECT
CONCAT(
'ALTER TABLE `',
TABLE_NAME,
'` ',
'MODIFY COLUMN `',
COLUMN_NAME,
'` ',
IF(UPPER(DATA_TYPE) = 'INT',
REPLACE(
SUBSTRING_INDEX(
UPPER(COLUMN_TYPE),
')',
1
),
'INT',
'INTEGER'
),
UPPER(COLUMN_TYPE)
),
') UNSIGNED NOT NULL AUTO_INCREMENT;'
)
FROMinformation_schema.COLUMNS
WHERETABLE_SCHEMA = 'source_database_name'AND
EXTRA = UPPER('AUTO_INCREMENT')
ORDERBYTABLE_NAME ASC

2. 导出所有索引:

    2.1 包括PRIMARY KEY和INDEX:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
SELECT
CONCAT('ALTER TABLE `',TABLE_NAME,'` ','ADD ',
 IF(NON_UNIQUE = 1,
 CASEUPPER(INDEX_TYPE)
 WHEN'FULLTEXT'THEN 'FULLTEXT INDEX'
 WHEN'SPATIAL'THEN 'SPATIAL INDEX'
 ELSECONCAT('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(DISTINCTCONCAT('`', COLUMN_NAME, '`')ORDERBYSEQ_IN_INDEX ASCSEPARATOR', '),');')AS'Show_Add_Indexes'
FROMinformation_schema.STATISTICS
WHERETABLE_SCHEMA = 'source_database_name'
GROUPBYTABLE_NAME, INDEX_NAME
ORDERBYTABLE_NAME ASC, INDEX_NAME ASC


  2.2 不包括PRIMARY KEY,只包含INDEX:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
SELECT
CONCAT('ALTER TABLE `',TABLE_NAME,'` ','ADD ',
 IF(NON_UNIQUE = 1,
 CASEUPPER(INDEX_TYPE)
 WHEN'FULLTEXT'THEN 'FULLTEXT INDEX'
 WHEN'SPATIAL'THEN 'SPATIAL INDEX'
 ELSECONCAT('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(DISTINCTCONCAT('`', COLUMN_NAME, '`')ORDERBYSEQ_IN_INDEX ASCSEPARATOR', '),');')AS'Show_Add_Indexes'
FROMinformation_schema.STATISTICS
WHERETABLE_SCHEMA = 'source_database_name'
AND UPPER(INDEX_NAME) != 'PRIMARY'
GROUPBYTABLE_NAME, INDEX_NAME
ORDERBYTABLE_NAME ASC, INDEX_NAME ASC







3. 创建删除所有自增字段:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
SELECT
CONCAT(
'ALTER TABLE `',
TABLE_NAME,
'` ',
'MODIFY COLUMN `',
COLUMN_NAME,
'` ',
IF(UPPER(DATA_TYPE) = 'INT',
REPLACE(
SUBSTRING_INDEX(
UPPER(COLUMN_TYPE),
')',
1
),
'INT',
'INTEGER'
),
UPPER(COLUMN_TYPE)
),
') UNSIGNED NOT NULL;'
)
FROMinformation_schema.COLUMNS
WHERETABLE_SCHEMA = 'destination_database_name'AND
EXTRA = UPPER('AUTO_INCREMENT')
ORDERBYTABLE_NAME ASC

4. 删除库所有索引:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
SELECT
CONCAT(
'ALTER TABLE `',
TABLE_NAME,
'` ',
GROUP_CONCAT(
DISTINCT
CONCAT(
'DROP ',
IF(UPPER(INDEX_NAME) = 'PRIMARY',
'PRIMARY KEY',
CONCAT('INDEX `', INDEX_NAME, '`')
)
)
SEPARATOR', '
),
';'
)
FROMinformation_schema.STATISTICS
WHERETABLE_SCHEMA = 'destination_database_name'
GROUPBYTABLE_NAME
ORDERBYTABLE_NAME ASC
展开阅读全文

没有更多推荐了,返回首页