一些 Mysql 维护命令
Posted Jerry_Jin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了一些 Mysql 维护命令相关的知识,希望对你有一定的参考价值。
---------------------------------------------------------
-------------------使用mysql客户端程序-------------------
---------------------------------------------------------
-------------------建立MySQL用户帐户-------------------
--登录mysql
mysql -h hostname -u username -p password;
mysql --host=localhost --user=root --password
--创建账户并授予数据库访问权限
grant all on dbname.* to \'username\'@\'hostname\' identified by \'password\';
--查看MySQL帮助
mysql --help
-------------------创建数据库表和样表-------------------
--创建数据库
create database dbname;
--切换当前使用数据库
use dbname;
--创建表
create table limbs (thing varchar(20), legs int, arms int);
--插入数据
insert into limbs(thing, legs, arms) values(\'human\', 2, 2);
insert into limbs(thing, legs, arms) values(\'insect\', 6, 0);
insert into limbs(thing, legs, arms) values(\'squid\', 0, 10);
insert into limbs(thing, legs, arms) values(\'octopus\', 0, 8);
insert into limbs(thing, legs, arms) values(\'fish\', 0, 0);
insert into limbs(thing, legs, arms) values(\'centipede\', 100, 0);
insert into limbs(thing, legs, arms) values(\'table\', 4, 0);
insert into limbs(thing, legs, arms) values(\'armchair\', 4, 2);
insert into limbs(thing, legs, arms) values(\'phonograph\', 0, 1);
insert into limbs(thing, legs, arms) values(\'tripod\', 3, 0);
insert into limbs(thing, legs, arms) values(\'Peg Leg Pete\', 1, 2);
insert into limbs(thing, legs, arms) values(\'space alien\', null, null);
--查询数据
select * from limbs;
-------------------启动和停止MySQL-------------------
--备份数据库
mysqldump -h localhost -u username -p daname > dbname.sql
mysqldump -h localhost -u cbuser -p cookbook > cookbook.sql
mysqldump -h srchost -uusername -ppassword srcdbname | mysql -hdsthost -uusername -p dstdbname
mysqldump -h192.168.62.68 -uroot -p** text | mysql -h127.0.0.1 -uroot -p test
mysqldump -h192.168.71.137 -uroot -p** love | mysql -h127.0.0.1 -uroot -p love
--shutdown数据库服务器
mysqladmin -p -u root shutdown
--退出MySQL
quit;
exit;
--操作系统服务方式启动停止mysql(vista\\win7管理员方式启动cmd)
net start mysql
net stop mysql
--操作系统服务方式启动停止mysql(linux管理员方式启动cmd)
service mysqld start
service mysqld stop
-------------------使用可选项文件来指定连接参数-------------------
--通用客户端程序连接选项
[client]
host=localhost
user=cbuser
password=cbpass
--mysql特定选项
[mysql]
skip-auto-rehash
--查看从选项文件读取哪些选项
mysql --print-defaults
--检查从选项文件读取了什么值
my_print_defaults client mysql
-------------------保护选项文件以阻止其他用户读取-------------------
chmod 60 .my.cnf
chmod go-rwx .my.cnf
-------------------发起sql语句-------------------
--分号;结束
select * from tables;
--\\g结束
select * from table\\g
-------------------取消一条部分输入的语句-------------------
--\\c取消
select *
from tables
where fun \\c
--/* */注释
select * /* this is comments*/
from tables
where fun \\c
-------------------重复和编辑sql语句-------------------
up 向上翻动语句的历史
down 向下翻动语句的历史
left 行内左移
right 行内右移
backspace 删除前一个字符
-------------------自动完成数据库和表名-------------------
-------------------让mysql从文件中读取语句-----------------
--cmd从sql文件中读取
mysql dbname < filename
mysql cookbook < limbs.sql
--mysql会话内从sql文件读取
source filename
\\. filename
source testscore.sql
\\. testscore.sql
--测试.sql文件中调用脚本文件可嵌套层数
create table counter (depth int);
insert into counter set depth = 0;
--loop.sql文件内容
update counter set depth = depth + 1;
select depth from counter;
source loop.sql;
--cmd调用loop.sql文件
mysql cookbook < loop.sql
--mysql会话调用loop.sql文件
source loop.sql
\\. loop.sql
--cmd查看系统错误号描述
perror 24
-------------------让mysql从其他程序读取语句-----------------
--cmd从pipe(管道)读取语句
type filename | mysql dbname /*cmd*/
cat filename | mysql dbname /*shell*/
type limbs.sql | mysql cookbook
cat limbs.sql | mysql cookbook
--结合mysqldump和mysql拷贝一个数据库到另外一个mysql服务器
mysqldump dbname | mysql -h some.other.host.com other_dbname
mysqldump cookbook | mysql -h other.host cookbook
--使用程序生成sql语句发送到mysql
generate-test-data | mysql cookbook
-------------------一行输入所有sql-----------------
--cmd一行输入sql
mysql -e "statement1" dbname -u username -p password
mysql -e "select count(*) from limbs" cookbook -uroot -p password
--cmd一行输入多个sql
mysql -e "statement1; statement2" dbname -u username -p password
mysql -e "select count(*) from limbs;,select now()" cookbook -uroot -p password
-------------------预防查询输出超出屏幕范围-----------------
--为mysql设置分页显示程序
mysql --pager=/usr/bin/less
mysql --pager /*已经设置环境变量pager*/
--mysql命令行开启关闭分页功能
\\p /*开启分页功能*/
\\p /usr/bin/less
\\n /*关闭分页功能*/
-------------------发送查询输出到文件或程序-----------------
--交互模式下表格显示结果集数据
select * from limbs
--非交互模式下制表符显示结果集数据
echo select * from limbs | mysql cookbook
--将mysql输出保存到文件
mysql dbname > outputfile
statement1;
statement2;
exit
mysql cookbook > d:\\result.txt
select * from limbs;
select * from testscore;
exit
--从指定文件读入sql,将结果保存到指定文件
mysql dbname < inputfile > outfile
mysql cookbook < test.txt > d:\\result.txt
--从指定文件读入sql,将结果发送到另一程序
mysql dbname < inputfile | mail paul
mysql dbname < test.txt | more
mysql cookbook < test.txt | find "alien" /*cmd*/
mysql cookbook < test.txt | grep "alien" /*linux*/
-------------------选择表格或制表符定界的查询输出格式-----------------
mysql -t dbname < inputfile
mysql -t cookbook < test.txt
mysql -t dbname < inputfile | program
mysql -t cookbook < test.txt | find "a"
-------------------指定任意的输出列分隔符-----------------
mysql cookbook < test.sql | sed -e "s/TAB/:/g" > result.txt
mysql cookbook < test.sql | tr " TAB" ":" > result.txt
mysql cookbook < test.sql | tr "\\011" ":" > result.txt
-------------------生成xml或html-----------------
mysql -H -e "statement" dbname > outfile
mysql -X -e "statement" dbname > outfile
mysql -H -e "select * from limbs" cookbook > demohtml.txt
mysql -X -e "select * from limbs" cookbook > demoxml.txt
-------------------使长输出行更具有可读性-----------------
--mysql命令行垂直显示结果集
show full columns from tables;
show full columns from tables\\g
show full columns from tables\\G /*局部控制垂直显示方式*/
--cmd命令行垂直显示结果集
mysql -E /*全局控制垂直显示方式*/
-------------------控制mysql的繁冗级别-----------------
echo select now() | mysql /*cmd*/
echo select now() | mysql -v /*cmd*/
echo select now() | mysql -vv /*cmd*/
echo select now() | mysql -vvv /*cmd*/
echo "select now()" | mysql /*linux*/
echo "select now()" | mysql -v /*linux*/
echo "select now()" | mysql -vv /*linux*/
echo "select now()" | mysql -vvv /*linux*/
-------------------记录交互式的mysql会话-----------------
--cmd命令行记录交互日志到指定文件
mysql -tee=outfile dbname
mysql -tee=tmp.out cookbook
--\\T开启交互日志功能、\\t关闭日志交互功能
-------------------以之前执行的语句创建mysql脚本-----------------
--使用mysql执行语句历史文件.mysql_history(位于用户home目录下)
cd; cat .mysql_history
-------------------在sql语句中使用用户自定义的变量-----------------
--将select列值赋予变量
select @class_id := id from t_classes where id = 2;
delete from t_student where classesid = @class_id;
delete from t_classes where id = @class_id;
--将表达式至赋予变量
select @max_limbs := max(arms+legs) from limbs;
--将含有auto_increment列的表插入新行之后的last_insert_id()的结果赋给变量
select @last_id := last_insert_id();
--如果查询返回值含有多行,最后一行的值赋予变量
select @name := thing from limbs where legs = 0;
select @name;
--如果语句没有返回任何行,变量保持先前值,如果先前没有赋值,则为null
select @name2 := thing from limbs where legs < 0;
--使用set显式为某个变量指定特定值
set @sum = 4 + 7;
select @sum;
set @sum2 := 3 + 2;
select @sum2;
--使用set将一个select结果赋给变量
set @max_limbs = (select max(arms+legs) from limbs);
--变量名不区分大小写
set @x = 1, @X = 2;
select @x, @X;
-------------------为查询输出行计数-----------------
--linux命令行--skip-column-names结合cat -n
mysql --skip-column-names -e "select thing, arms from limbs" cookbook | cat -n
--mysql命令行使用自定义变量
set @n = 0;
select @n := @n + 1 as rownum, thing, arms, legs from limbs;
-------------------将mysql用作计算器-----------------
select (17 + 24) / sqrt(64);
select "ABC" = "abc";
select "ABC" = "abcd";
set @daily_room_charge = 100.00;
set @num_of_nights = 3;
set @tax_percent = 8;
set @total_room_charge = @daily_room_charge * @num_of_nights;
set @tax = (@total_room_charge * @tax_percent) / 100;
set @total = @total_room_charge + @tax;
select @total;
-------------------在unix下写shell脚本-----------------
--shell脚本查看mysql服务器正常运行时间
#!/bin/sh
# mysql_uptime.sh - report server uptime in seconds
mysql --skip-column-names -B -e "SHOW /*!50002 GLOBAL */ STATUS LIKE \'Uptime\'"
#!/bin/sh
# mysql_uptime2.sh - report server uptime
mysql -e STATUS | grep "^Uptime"
#!/bin/sh
# mysql_uptime3.sh - report server uptime
echo STATUS | mysql | grep "^Uptime"
--mysql命令行查看mysql服务器正常运行时间
status
--win环境下安装类unix命令行环境
cygnus
uwin
---------------------------------------------------------
---------------------从表中查询数据----------------------
---------------------------------------------------------
--查询数据库版本、当前会话默认数据库名
select version(), database();
--创建表
CREATE TABLE mail
(
t DATETIME, # when message was sent
srcuser CHAR(8), # sender (source user and host)
srchost CHAR(20),
dstuser CHAR(8), # recipient (destination user and host)
dsthost CHAR(20),
size BIGINT, # message size in bytes
INDEX (t)
);
--插入数据
INSERT INTO mail (t,srchost,srcuser,dsthost,dstuser,size)
VALUES
(\'2006-05-11 10:15:08\',\'saturn\',\'barb\',\'mars\',\'tricia\',58274),
(\'2006-05-12 12:48:13\',\'mars\',\'tricia\',\'venus\',\'gene\',194925),
(\'2006-05-12 15:02:49\',\'mars\',\'phil\',\'saturn\',\'phil\',1048),
(\'2006-05-13 13:59:18\',\'saturn\',\'barb\',\'venus\',\'tricia\',271),
(\'2006-05-14 09:31:37\',\'venus\',\'gene\',\'mars\',\'barb\',2291),
(\'2006-05-14 11:52:17\',\'mars\',\'phil\',\'saturn\',\'tricia\',5781),
(\'2006-05-14 14:42:21\',\'venus\',\'barb\',\'venus\',\'barb\',98151),
(\'2006-05-14 17:03:01\',\'saturn\',\'tricia\',\'venus\',\'phil\',2394482),
(\'2006-05-15 07:17:48\',\'mars\',\'gene\',\'saturn\',\'gene\',3824),
(\'2006-05-15 08:50:57\',\'venus\',\'phil\',\'venus\',\'phil\',978),
(\'2006-05-15 10:25:52\',\'mars\',\'gene\',\'saturn\',\'tricia\',998532),
(\'2006-05-15 17:35:31\',\'saturn\',\'gene\',\'mars\',\'gene\',3856),
(\'2006-05-16 09:00:28\',\'venus\',\'gene\',\'mars\',\'barb\',613),
(\'2006-05-16 23:04:19\',\'venus\',\'phil\',\'venus\',\'barb\',10294),
(\'2006-05-17 12:49:23\',\'mars\',\'phil\',\'saturn\',\'tricia\',873),
(\'2006-05-19 22:21:51\',\'saturn\',\'gene\',\'venus\',\'gene\',23992)
;
----------------指定查询列/从指定列中查询-----------------
select * from mail;
select t, srchost, srcuser, dsthost, dstuser, size from mail;
select t, srcuser, srchost, size from mail;
------------------------指定查询行-------------------------
select t, srcuser, srchost from mail where srchost = "venus";
select t, srcuser, srchost from mail where srchost like \'s%\';
select * from mail where srcuser = \'barb\' and dstuser = \'tricia\';
---------------------格式化显示查询结果----------------------
select t, srcuser, size from mail;
select concat(monthname(t), \' \', dayofmonth(t), \', \', year(t)), srcuser, size from mail;
select date_format(t, \'%M %e, %Y\'), srcuser, size from mail;
select date_format(t, \'%M %e, %Y\') as \'Date of message\',
srcuser as \'Message sendr\',
size as \'Number of bytes\'
from mail;
select \'1+1+1\' as \'The epression\', 1+1+1 as \'The result\';
select 1 as \'integer\';
---------------------合并多列来构建复合值----------------------
select date_format(t, \'%M %e, %Y\') as date_sent,
concat(srcuser, \'@\', srchost) as sender,
concat(dstuser, \'@\', dsthost) as recipient,
size
from mail;
---------------------where表达式中的列别名----------------------
select t, srcuser, dstuser, size/1024 as kilobytes
from mail where kilobytes > 500;
select t, srcuser, dstuser, size/1024 as kilobytes
from mail where size/1024 > 500;
---------------------调试比较表达式----------------------
select * from mail where srcuser < \'c\' and size > 500;
select srcuser, srcuser < \'c\', size, size > 500 from mail;
select srcuser, srcuser < \'c\', size, size > 500 from mail where srcuser < \'c\' and size > 500;
---------------------使查询结果唯一化---------------------
select srcuser from mail;
select distinct srcuser from mail;
select distinct year(t), month(t), dayofmonth(t) from mail;
select count(distinct srcuser) from mail;
----------------------如何处理null值-----------------------
--创建表
CREATE TABLE taxpayer
(
name CHAR(20),
id CHAR(20)
);
--插入数据
INSERT INTO taxpayer (name,id) VALUES (\'bernina\',\'198-48\');
INSERT INTO taxpayer (name,id) VALUES (\'bertha\',NULL);
INSERT INTO taxpayer (name,id) VALUES (\'ben\',NULL);
INSERT INTO taxpayer (name,id) VALUES (\'bill\',\'475-83\');
select * from taxpayer;
select * from taxpayer where id = null;
select * from taxpayer where id != null;
select * from taxpayer where id is null;
select * from taxpayer where id is not null;
select null = null, null <=> null;
select if(id is null, "unknown", id) as \'id\' from taxpayer;
select name, ifnull(id, \'unknown\') as \'id\' from taxpayer;
----------------------结果集排序-----------------------
select * from mail where size > 1000000 order by size;
select * from mail where dstuser = \'tricia\' order by srchost, srcuser;
select * from mail where size > 50000 order by size desc;
----------------------使用视图简化查询-----------------------
select date_format(t, \'\') as date_sent,
concat(srcuser, \'@\', srchost) as sender,
concat(dstuser, \'@\', dsthost) as recipient,
size
from mail;
create view mail_view as
select date_format(t, \'%M %e, %Y\') as date_sent,
concat(srcuser, \'@\', srchost) as sender,
concat(dstuser, \'@\', dsthost) as recipient,
size
from mail;
select date_sent, sender, size from mail_view
where size > 100000
order by size;
----------------------多表查询-----------------------
--创建表
CREATE TABLE profile_contact
(
profile_id INT UNSIGNED NOT NULL, # ID from profile table
service CHAR(20) NOT NULL, # messaging service name
contact_name CHAR(25) NOT NULL, # name to use for contacting person
INDEX (profile_id)
);
--插入数据
INSERT INTO profile_contact
VALUES
(1, \'AIM\', \'user1-aimid\'),
(1, \'MSN\', \'user1-msnid\'),
(2, \'AIM\', \'user2-aimid\'),
(2, \'MSN\', \'user2-msnid\'),
(2, \'Yahoo\', \'user2-yahooid\'),
(4, \'Yahoo\', \'user4-yahooid\')
;
select * from profile_contact order by profile_id, service;
select id, name, service, contact_name
from profile inner join profile_contact on id = profile_id;
select * from profile_contact
where profile_id = (select id from profile where name = \'Mort\');
----------------------从查询结果集头或尾取出部分行-----------------------
select * from profile;
select * from profile limit 1;
select * from profile limit 5;
select * from profile order by birth limit 1;
select * from profile order by birth desc limit 1;
select name, date_format(birth, \'%m-%d\') as birthday
from profile
order by birthday
limit 1;
----------------------在结果集头中间选取部分行-----------------------
select * from profile order by birth limit 2, 1;
select * from profile order by birth desc limit 2, 1;
select count(*) from profile;
select * from profile order by name desc limit 0, 4;
select * from profile order by name desc limit 4, 4;
select * from profile order by name desc limit 8, 4;
select sql_calc_found_rows * from profile order by id limit 4;
select found_rows();
----------------------选择合适的limit参数-----------------------
--创建表
CREATE TABLE al_winner
(
name CHAR(30),
wins INT
);
--初始化数据 al_winner-2001.txt
Mulder, Mark 21
Clemens, Roger 20
Moyer, Jamie 20
Garcia, Freddy 18
Hudson, Tim 18
Abbott, Paul 17
Mays, Joe 17
Mussina, Mike 17
Sabathia, C.C. 17
Zito, Barry 17
Buehrle, Mark 16
Milton, Eric 15
Pettitte, Andy 15
Radke, Brad 15
Sele, Aaron 15
--导入数据数据
load data local infile \'al_winner-2001.txt\' into table al_winner;
set @n = 0;
set @val = 0;
select @n:=if(@val=wins, @n, @n+1) as rank,name, @val:=wins as wins
from al_winner order by wins desc, name;
selectname, wins from al_winner
order by wins desc, name;
select name, wins from al_winner
order by wins desc, name
limit 4;
select name, wins from al_winner
order by wins desc, name
limit 3, 1;
select name, wins from al_winner
where wins >= 18
order by wins desc, name;
select name, wins from al_winner
where wins >=
(
select wins from al_winner
order by wins desc, name
limit 3, 1
)
order by wins desc, name;
select distinct wins from al_winner
order by wins desc, name
limit 3, 1;
select name, wins from al_winner
where wins >= 17
order by wins desc, name;
select name, wins from al_winner
where wins >=
(
select distinct wins from al_winner
order by wins desc, name
limit 3, 1
)
order by wins desc, name;
----------------------当limit需要“错误”的排列顺序时做什么-----------------------
select name, birth from profile order by birth desc limit 4;
select count(*) from profle;
select name, birth from profile order by birth limit 6, 4;
select name, birth
from
(
select name, birth from profile order by birth desc limit 4
) as t
order by birth;
----------------------从表达式中计算limit值-----------------------
--limit只允许数字作为其参数,不能使用表达式
select * from profile limit 5+5;
select * from profile limit @skip_count, @show_count;
---------------------------------------------------------
--------------------------表关联-------------------------
---------------------------------------------------------
----------------------克隆表-----------------------------
--仅仅克隆表结构(不克隆源表外键定义)
create table new_table like original_table;
create table mail2 like mail;
select * from mail2;
--转移表数据
insert into new_table select * from original_table;
insert into mail2 select * from mail where srcuser = \'barb\';
select * from mail2;
----------------------将查询结果保存到表中-----------------------------
--如果目的表已经存在
insert into dsttbl(i, s) select val, name from src_tal;
insert into dst_tbl select * from src_tbl; /*目的表与源表结构相同,拷贝全部数据*/
insert into dst_tbl select * from src_tbl where val > 1000 and name like \'A%\'; /*目的表与源表结构相同,拷贝部分数据*/
insert into dst_tbl(i, s) select count(*), name from src_tbl group by name; /*目的表与基于源表进行统计的结果结构相同,将源表统计结果插入目的表*/
--如果目的表不存在
create table dst_tbl select * from src_tbl;
create table dst_tbl select * from src_tbl where 0; /*仅克隆表结构,不克隆约束、键等,不包含数据*/
create table dst_tbl select b, c from src_tbl; /*依照源表部分列建表*/
create table dst_tbl select c, b, a from src_tbl; /*改变源表列定义顺序(假设源表为a、b、c)*/
create table dst_tbl (id int not null auto_increment), primary key(id)) select a, b, c from src_tbl; /*在create table子句中插入列定义,此列不存在于源表中*/
/*
create table dst_tbl
(
id int not null auto_increment),
primary key(id)
)
select a, b, c from src_tbl;
*/
create table hoho
(
id int not null auto_increment,
primary key (id)
)
select * from limbs;
create table dst_tbl select inv_no, sum(unit_cost * quantity) as total_cost from src_tbl group by inv_no; /*在create table子句中为表达式赋予别名,此列不存在于源表中*/
/*
create table dst_tbl
select inv_no, sum(unit_cost * quantity) as total_cost
from src_tbl
group by inv_no;
*/
create table dst_tbl (primary key(id), index(state, city)) select * from src_tbl; /*根据源表定义目的表主键、索引,假设源表主键为id,state、city列上有索引*/
/*间接复制列属性与默认值*/
create table dst_tbl (primary key(id)) select * from src_tbl;
alter table dst_tbl modify id int unsigned not null auto_increment;
----------------------使用临时表-----------------------------
--普通建表
create temporary table tbl_name(...)
--克隆表
create temporary table new_table like original_table;
--根据查询结果建表
create temporary table tbl_name select ...;
--创建与已存在的表同名的临时表,暂时屏蔽非临时表
create temporary table mail select * from mail;
select count(*) from mail;
delete from mail;
select count(*) from mail;
drop table mail;
select count(*) from mail;
drop temporary table if exists tbl_name;
----------------------检查或改变某个表的存储引擎-----------------------------
--InnoDB BDB MyISAM
--检测information_schema
select engine from information_schema.tables where table_schema = \'cookbook\' and table_name = \'mail\';
show table status\\G
show table status like \'mail\'\\G
show create table mail\\G
--改变表引擎
alter table mail engine = InnoDB;
alter table mail engine = BDB;
alter table mail engine = MyISAM;
--生成唯一的表名
drop table if exists tbl_name;
select connection_id();
---------------------------------------------------------
----------------------与字符串共舞-----------------------
---------------------------------------------------------
----------------------字符串属性-------------------------
--查看系统支持字符集
show character set;
--查看字节长度、字符长度
set @s = convert(\'abc\' using ucs2);
select length(@s), char_length(@s);
set @s = convert(\'abc\' using utf8);
select length(@s), char_length(@s);
--查看collation
show collation;
--查看特定字符集collation
show collation like \'latin1%\';
--collation排序
create table t (c char(3) character set latin1);
insert into t (c) values(\'AAA\'), (\'bbb\'), (\'aaa\'), (\'BBB\');
select c from t;
--大小写不敏感
select c from t order by c collate latin1_swedish_ci;
--大小写敏感
select c from t order by c collate latin1_general_cs;
--二进制数值排序
select c from t order by c collate latin1_bin;
create table t(c char(2) character set utf8);
insert into t(c) values(\'cg\'), (\'ch\'), (\'ci\'), (\'lk\'), (\'ll\'), (\'lm\');
select c from t order by c collate utf8_general_ci;
select c from t order by c collate utf8_spanish2_ci;
----------------------选择字符串数据类型-------------------------
-----------------------------------------------------
二进制数据类型 非二进制数据类型 最大长度
binary char 255
varbinary varchar 65535
tinyblob tinytext 255
blob text 65535
mediumblob mediumtext 16777215
longblog longtext 4294967295
-----------------------------------------------------
--char与varchar处理尾部空格的差异之处
create table t (c1 char(10), c2 varchar(10));
insert into t (c1, c2) values(\'abc \', \'abc \');
select c1, c2, char_length(c1), char_length(c2) from t;
--指定列character set与collation
create table mytbl
(
utf8data varchar(100) character set utf8 collate utf8_danish_ci,
sjisdata varchar(100) character set sjis collate sjis_japanese_ci
);
--character-set-server
--collation-server
----------------------正确设置客户端连接的字符集-------------------------
--配置文件
[mysql]
default-character-set=utf-8
--mysql命令行
set names \'utf8\';
set names \'utf8\' collate \'utf8-general-ci\';
--编程接口:MySQL connectot/J, 应用程序连接URL
jdbc:mysql://localhost/cookbook?characterEncoding=UTF-8
----------------------串字母-------------------------
--定义字符串
\'my string\'
"my string" /*ansi_quotes 模式启用时双引号内的字符解释为表名或列名*/
--使用十六进制数标记abcd
0x6162364
x\'6162364\'
X\'6162364\'
insert into t set binary_col = 0xdeadbeef; /*sql中使用十六进制字符串指代二进制数值*/
--为字符串指定一个字符集解释器
_latin1 \'abcd\' /*包含四个单字节字符的字符串*/
_ucs2 \'abcd\' /*包含两个双字节字符的字符串*/
--包含单引号的字符串
select "I\'m asleep";
select \'I\'\'m asleep\';
select \'I\\\'m wide awake\';
--包含双引号的字符串
select \'He said, "Boo!"\';
select "He said, ""Bob!""";
select "And I said \\"Yikes!\\"";
--包含\\反斜线的字符串(特殊字符\\b,\\n,\\r,\\t,\\0,\\\\)
select \'Install MySQL in c:\\\\mysql on Windows\';
--使用十六进制数表示字符串
select 0x49276D2061736C656570;
----------------------检查一个字符串的字符集或字符排序-------------------------
--返回特定字符集和字符排序
select user(), charset(user()), collation(user());
--改变当前字符集影响普通字符串字符集和字符排序
set names \'latin1\';
select charset(\'abc\'), collation(\'abc\');
set names latin7 collate \'latin7_bin\';
select charset(\'abc\'), collation(\'abc\');
--返回二机制字符串
select charset(md5(\'a\')), collation(md5(\'a\'));
select charset(password(\'a\')), collation(password(\'a\'));
--转换二机制字符串结果大小写将失败
select upper(md5(\'a\')), lower(md5(\'a\'));
----------------------改变字符串的字符集或字符排序-------------------------
--改变字符集
set @s1 = "my string";
set @s2 = convert(@s1 using utf8);
select charset(@s1), charset(@s2);
--改变collation
set @s1 = \'my string\';
set @s2 = @s1 collate latin1_spanish_ci;
select collation(@s1), collation(@s2);
select _latin1 \'abc\' collate utf8_bin; /*出错,Collation对于字符串的字符集必须是合法的*/
set @s1 = "my string";
set @s2 = convert(@s1 using utf8) collate utf8_spanish_ci; /*正确,先转换字符集,再转换排序*/
select charset(@s1), collation(@s1), charset(@s2), collation(@s2);
--转换二进制字符串和非二进制字符串
set @s1 = \'my string\';
set @s2 = convert(@s1 using binary);
set @s3 = convert(@s2 using utf8);
select charset(@s1), charset(@s2), charset(@s3);
--binary操作符产生二进制字符串
set @s1 = \'my string\';
set @s2 = binary @s2; /*与convert(str using binary)等效*/
select charset(@s1), charset(@s2);
----------------------更改字符串字母的大小写-------------------------
--整体替换大小写
select thing, upper(thing), lower(thing) from limbs;
--局部修改大小写
select thing, concat(upper(left(thing, 1)), mid(thing, 2)) from limbs;
--自定义函数局部修改大小写
create function initial_cap(s varchar(255))
returns varchar(255) deterministic
return concat(upper(left(s, 1)), mid(s, 2));
select thing, initial_cap(thing) from limbs;
----------------------更改字符串字母的大小写失败处理情况-------------------------
--改变非二进制字符串大小写
set @s = \'aBcD\';
select upper(@s), lower(@s);
--改变二进制字符串大小写
drop table if exists t;
create table t(b blob) select \'aBcD\' as b;
select b, upper(b), lower(b) from t; /*upper、lower改变二进制字符串大小写不生效*/
set @s = binary \'aBcD\';
select @s, lower(@s), upper(@s); /*MySQL4.1之前生效*/
select b, upper(convert(b using latin1)) as upper, lower(convert(b using latin1)) as lower from t; /*先转换二进制字符串到非二机制字符串,再进行大小写转换*/
select charset(version()), charset(md5(\'some string\'));
select upper(version());
select md5(\'some thing\'), upper(convert(md5(\'some thing\') using latin1));
----------------------控制字符串比较中的大小写敏感------------------------- 以上是关于一些 Mysql 维护命令的主要内容,如果未能解决你的问题,请参考以下文章
select \'cat\' = \'cat\', \'cat\' = \'dpg\';
select \'cat\' != \'cat\', \'cat\' != \'dpg\';
select \'cat\' < \'awk\', \'cat\' < \'dpg\';
select \'cat\' between \'awk\' and \'egret\';
set @s1 = binary \'cat\', @s2 = binary \'CAT\';
select @s1 = @s2; /*二进制字符串比较大小写敏感,结果不等*/
set @s1 = convert(@s1 using latin1) collate latin1_swedish_ci;
set @s2 = convert(@s2 using latin1) collate latin1_swedish_ci;
select @s1 = @s2; /*转换成非二进制字符串,并指定字符集collation大小写不敏感,结果相等*/
/*latin1默认collation为latin1_swedish_ci*/
set @s1 = convert(@s1 using latin1);
set @s2 = convert(@s2 using latin1);
select @s1 = @s2;
set @s1 = _latin1 \'cat\', @s2 = _latin1 \'CAT\';
select @s1 = @s2;
select @s1 collate latin1_general_cs = @s2 collate latin1_general_cs as \'@s1 = @s2\';
select _latin1 \'cat\' = binary \'CAT\';
set @s1 = _latin1 \'cat\', @s2 = _latin1 \'CAT\';
select @s1 = @s2, binary @s1 = @s2, @s1 = binary @s2;
--修改表定义,改变列大小写敏感模式
create table new
(
id int unsigned not null auto_increment,
article blob, /*大小写敏感*/
primary key(id)
);
alter table news
modify article text charcter set utf8 collate utf_general_ci; /*大小写不敏感*/
----------------------使用sql模式进行模式匹配-------------------------
--消除可能存在的表冲突
drop table if exists metal;
--创建表
create table metal (name varchar(20));
--初始化表数据
insert into metal (name) values(\'copper\'), (\'gold\'), (\'iron\'), (\'lead\'), (\'mercury\'), (\'platinum\'), (\'silver\'), (\'tin\');
--查询初始化数据
select * from metal;
--查询以特定字符开头的字符串
select name from metal where name like \'co%\';
--查询以特定字符结尾的字符串
select name from metal where name like \'%er\';
--查询含有特定字符的字符串