如何更改数据库,表,列的排序规则?


Answers:


257

您需要分别转换每个表:

ALTER TABLE mytable CONVERT TO CHARACTER SET utf8mb4 

(这也将转换列),或使用导出数据库,latin1然后使用将其导入回来utf8mb4


15
但是我想更改列的排序规则。这将仅更改表排序
规则。–

7
@rsensanCONVERT也将更改列的排序规则。
Quassnoi

21
更改模式database 默认字符集utf8默认集合utf8_general_ci;
暴风雨

8
@stormwild:这不会影响现有的表格
Quassnoi

47
我的查询:ALTER TABLE MYTABLECONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; 请不要再使用utf8_general_ci ;-)
Kapitein Witbaard 2015年

209

我在此做出贡献,正如OP所问的那样:

如何更改数据库,表,列的排序规则?

所选答案仅在表级别上说明。


在数据库范围内更改它:

ALTER DATABASE <database_name> CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

更改每个表:

ALTER TABLE <table_name> CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

优良作法是在表级别进行更改,因为它也会在列中进行更改。更改特定列适用于任何特定情况。

更改特定列的排序规则:

ALTER TABLE <table_name> MODIFY <column_name> VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

15
这实际上直接回答了这个问题。我需要这样做,因为我的表级更改不会更新列。我待会再调查;但这是使我度过艰难时期的信息。谢谢。
Parapluie

9
最好的答案。
jubi4dition

是的,您需要指定列类型。这是获取所有类型的魔术命令。使用多行编辑,您可以从此处开始生成一次更新所有列的命令:SELECT table_schema , table_name , column_name , COLLATION_NAME , COLUMN_TYPE FROM information_schema.columns WHERE collation_name != 'utf8_general_ci' AND table_schema not in ('information_schema','mysql', 'performance_schema','sys');
William Entriken

对于单个列,您可以简单地执行以下操作:ALTER TABLE table_name CHANGE column_name VARCHAR(45)COLLATE utf8mb4_bin;
TomoMiha

68

您可以运行php脚本。

               <?php
                   $con = mysql_connect('localhost','user','password');
                   if(!$con) { echo "Cannot connect to the database ";die();}
                   mysql_select_db('dbname');
                   $result=mysql_query('show tables');
                   while($tables = mysql_fetch_array($result)) {
                            foreach ($tables as $key => $value) {
                             mysql_query("ALTER TABLE $value CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci");
                       }}
                   echo "The collation of your database has been successfully changed!";
                ?>

43

要单独更改表格的排序规则,可以使用,

ALTER TABLE mytable CONVERT TO CHARACTER SET utf8

要为整个数据库设置默认排序规则,

ALTER DATABASE  `databasename` DEFAULT CHARACTER SET utf8 COLLATE utf8_bin

要不然,

转到PhpMyAdmin->操作->整理。

在这里,您将找到一个包含所有现有归类的选择框。这样您就可以在这里更改排序规则。因此,在此之后,数据库表将在创建新列时遵循此排序规则。创建新列时无需选择排序规则。


非常感谢,这很有帮助
JoZ3

15

以下查询将生成ALTER查询,该查询将所有表中所有适当列的排序规则更改为某种类型(在下面的示例中为utf8_general_ci)。

SELECT concat
        (
            'ALTER TABLE ', 
                t1.TABLE_SCHEMA, 
                '.', 
                t1.table_name, 
                ' MODIFY ', 
                t1.column_name, 
                ' ', 
                t1.data_type, 
                '(' , 
                    CHARACTER_MAXIMUM_LENGTH, 
                ')', 
                ' CHARACTER SET utf8 COLLATE utf8_general_ci;'
        )
from 
    information_schema.columns t1
where 
    t1.TABLE_SCHEMA like 'you_db_name_goes_here' AND
    t1.COLLATION_NAME IS NOT NULL AND
    t1.COLLATION_NAME NOT IN ('utf8_general_ci');

+1我最喜欢这个答案。并非每个人都在某个地方拥有PHP。一些使用MySQL的人使用其他语言。这很容易在MySQL Workbench中运行,复制行并粘贴。我只是做了额外的步骤来运行上面information_schema.tables的代码和concat中的代码ALTER TABLE 'schema'.'table' CHARACTER SET = utf8mb4 , COLLATE = utf8mb4_bin ;
Pierre

1
这会导致(中/长)文本列类型
出错

11

如果您运行phpMyAdmin >>选择数据库>>选择表>>转到“操作”选项卡>>在“表选项”部分>>您可以从下拉列表中选择“排序规则”,然后在在屏幕顶部,您将看到一条消息:

您的SQL查询已成功执行

和一个脚本

ALTER TABLE `tableName` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci 

但这不会更改现有列的排序规则。为此,您可以使用此脚本(该脚本也来自phpMyAdmin)

ALTER TABLE  `tableName` CHANGE  `Name`  `Name` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL


5

只需运行此SQL即可一次转换所有数据库表。将您的COLLATION和databaseName更改为所需。

SELECT CONCAT("ALTER TABLE ", TABLE_SCHEMA, '.', TABLE_NAME," COLLATE utf8_general_ci;") AS    ExecuteTheString
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA="databaseName"
AND TABLE_TYPE="BASE TABLE";

4

您可以通过PHP脚本如下更改所有表的CHARSET和COLLATION。我喜欢hkasera的答案,但问题在于查询在每个表上运行两次。除了使用MySqli代替mysql并防止重复查询外,这段代码几乎相同。如果我可以投票,我本来会投票赞成hkasera的。

<?php
$conn1=new MySQLi("localhost","user","password","database");
if($conn1->connect_errno){
    echo mysqli_connect_error();
    exit;
}
$res=$conn1->query("show tables") or die($conn1->error);
while($tables=$res->fetch_array()){
    $conn1->query("ALTER TABLE $tables[0] CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci") or die($conn1->error);
}
echo "The collation of your database has been successfully changed!";

$res->free();
$conn1->close();

?>

升级到Zabbix 5后,这对我来说非常有效。这只是说我像这样更改了字符集排序规则CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin
robe007

4

您可以简单地将此代码添加到脚本文件

//Database Connection
$host = 'localhost';
$db_name = 'your_database_name';
$db_user =  'your_database_user_name';
$db_pass = 'your_database_user_password';

$con = mysql_connect($host,$db_user,$db_pass);

if(!$con) { echo "Cannot connect to the database ";die();}

  mysql_select_db($db_name);

  $result=mysql_query('show tables');

  while($tables = mysql_fetch_array($result)) {
    foreach ($tables as $key => $value) {
    mysql_query("ALTER TABLE $value CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci");
  }
}

echo "The collation of your database has been successfully changed!";

4

我很惊讶地学习,因此我不得不回到这里报告一下,出色且维护良好的互连/安全数据库搜索和替换脚本具有一些选项,可以将表转换为utf8 / unicode,甚至可以转换为innodb。 。它是一种脚本,通常用于将数据库驱动的网站(Wordpress,Drupal,Joomla等)从一个域迁移到另一个域。

互连脚本按钮


3

我在这里读到它,您需要手动转换每个表,这是不正确的。这是一个解决方案,如何使用存储过程:

DELIMITER $$

DROP PROCEDURE IF EXISTS changeCollation$$

-- character_set parameter could be 'utf8'
-- or 'latin1' or any other valid character set
CREATE PROCEDURE changeCollation(IN character_set VARCHAR(255))
BEGIN
DECLARE v_finished INTEGER DEFAULT 0;
DECLARE v_table_name varchar(255) DEFAULT "";
DECLARE v_message varchar(4000) DEFAULT "No records";

-- This will create a cursor that selects each table,
-- where the character set is not the one
-- that is defined in the parameter

DECLARE alter_cursor CURSOR FOR SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE()
AND COLLATION_NAME NOT LIKE CONCAT(character_set, '_%');

-- This handler will set the value v_finished to 1
-- if there are no more rows

DECLARE CONTINUE HANDLER
FOR NOT FOUND SET v_finished = 1;

OPEN alter_cursor;

-- Start a loop to fetch each rows from the cursor
get_table: LOOP

-- Fetch the table names one by one
FETCH alter_cursor INTO v_table_name;

-- If there is no more record, then we have to skip
-- the commands inside the loop
IF v_finished = 1 THEN
LEAVE get_table;
END IF;

IF v_table_name != '' THEN

IF v_message = 'No records' THEN
SET v_message = '';
END IF;

-- This technic makes the trick, it prepares a statement
-- that is based on the v_table_name parameter and it means
-- that this one is different by each iteration inside the loop

SET @s = CONCAT('ALTER TABLE ',v_table_name,
' CONVERT TO CHARACTER SET ', character_set);
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET v_message = CONCAT('The table ', v_table_name ,
' was changed to the default collation of ', character_set,
'.\n', v_message);

SET v_table_name = '';

END IF;
-- Close the loop and the cursor
END LOOP get_table;
CLOSE alter_cursor;

-- Returns information about the altered tables or 'No records'
SELECT v_message;

END $$

DELIMITER ;

创建过程后,只需简单地调用它:

CALL changeCollation('utf8');

有关更多详细信息,请阅读此博客


2

如果要更新架构上的默认字符集,请执行以下操作:

 ALTER SCHEMA MYSCHEMA DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_unicode_ci;

1

我使用了以下shell脚本。它以数据库名称为参数,并将所有表转换为另一个字符集和排序规则(由脚本中定义的另一个参数或默认值提供)。

#!/bin/bash

# mycollate.sh <database> [<charset> <collation>]
# changes MySQL/MariaDB charset and collation for one database - all tables and
# all columns in all tables

DB="$1"
CHARSET="$2"
COLL="$3"

[ -n "$DB" ] || exit 1
[ -n "$CHARSET" ] || CHARSET="utf8mb4"
[ -n "$COLL" ] || COLL="utf8mb4_general_ci"

echo $DB
echo "ALTER DATABASE $DB CHARACTER SET $CHARSET COLLATE $COLL;" | mysql

echo "USE $DB; SHOW TABLES;" | mysql -s | (
    while read TABLE; do
        echo $DB.$TABLE
        echo "ALTER TABLE $TABLE CONVERT TO CHARACTER SET $CHARSET COLLATE $COLL;" | mysql $DB
    done
)

1

我的解决方案是@Dzintars和@Quassnoi Answer的组合。

SELECT CONCAT("ALTER TABLE ", TABLE_SCHEMA, '.', TABLE_NAME," CONVERT TO CHARACTER SET utf8mb4 ;") AS    ExecuteTheString
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA="<your-database>"
AND TABLE_TYPE="BASE TABLE";

通过使用CONVERT TO,这将生成一个脚本,该脚本会将的所有表转换<your-database>为您请求的编码。这也会更改每列的编码!


1

通过SQL请求生成SQL脚本的更好变体。它不会破坏默认值/空值。

SELECT concat
    (
        'ALTER TABLE ', 
            t1.TABLE_SCHEMA, 
            '.', 
            t1.table_name, 
            ' MODIFY ', 
            t1.column_name, 
            ' ', 
            t1.column_type,
            ' CHARACTER SET utf8 COLLATE utf8_general_ci',
            if(t1.is_nullable='YES', ' NULL', ' NOT NULL'),
            if(t1.column_default is not null, concat(' DEFAULT \'', t1.column_default, '\''), ''),
            ';'
    )
from 
    information_schema.columns t1
where 
    t1.TABLE_SCHEMA like 'your_table_here' AND
    t1.COLLATION_NAME IS NOT NULL AND
    t1.COLLATION_NAME NOT IN ('utf8_general_ci');

0

快速方法-导出到SQL文件,使用搜索和替换来更改需要更改的文本。创建新数据库,导入数据,然后将旧数据库和新数据库重命名为旧名称。


0

一次更改数据库所有表中所有字段的排序规则:

我只是在前面提到的通过Php将表中字段的另一个循环添加到解决方案中。这有所帮助,表中的所有字段也都进行了转换。

<?php
$con = mysql_connect('localhost','user','pw');
if(!$con) { echo "Cannot connect to the database ";die();}
mysql_select_db('database_name');
$result=mysql_query('show tables');
while($tables = mysql_fetch_array($result)) {

foreach ($tables as $key => $table) {                   // for each table

    $sql = "ALTER TABLE $table CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci";
    echo "\n".$sql;
    mysql_query($sql);

    $sql = "show fields in ".$table." where type like 'varchar%' or type like 'char%' or type='text' or type='mediumtext';";
    $rs2=mysql_query($sql);
    while( $rw2 = mysql_fetch_array($rs2) ){            // for each field in table

        $sql = "ALTER TABLE `".$table."` CHANGE `".$rw2['Field']."` `".$rw2['Field']."` ".$rw2['Type']." CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;";
        echo "\n".$sql;
        mysql_query($sql);

    } 


}
}
echo "The collation of your database has been successfully changed!";

?>}

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.