数据库操作

create

mysql> create database study_2;
Query OK, 1 row affected (0.00 sec) mysql> show create database study_2;
+----------+--------------------------------------------------------------------+
| Database | Create Database |
+----------+--------------------------------------------------------------------+
| study_2 | CREATE DATABASE `study_2` /*!40100 DEFAULT CHARACTER SET latin1 */ |
+----------+--------------------------------------------------------------------+
1 row in set (0.00 sec)

上面的创建数据库是我们发现mysql默认的字符集是latin1,如果我们需要使用utf8的字符集创建数据库则使用下面的方法:

mysql> create database study_3 character set  utf8;
Query OK, 1 row affected (0.00 sec) mysql> show create database study_3;
+----------+------------------------------------------------------------------+
| Database | Create Database |
+----------+------------------------------------------------------------------+
| study_3 | CREATE DATABASE `study_3` /*!40100 DEFAULT CHARACTER SET utf8 */ |
+----------+------------------------------------------------------------------+
1 row in set (0.00 sec)

我们可以在my.cnf中设置mysql的字符集:

[client]
default_character_set=utf8
[mysqld]
default_character_set=utf8

还可以使用下面的SQL命令查看数据的字符集参数:

mysql>  show variables like 'character_set_%';
+--------------------------+---------------------------------------------------------------+
| Variable_name | Value |
+--------------------------+---------------------------------------------------------------+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | latin1 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | latin1 |
| character_set_system | utf8 |
| character_sets_dir | /usr/local/mysql-5.6.31-linux-glibc2.5-x86_64/share/charsets/ |
+--------------------------+---------------------------------------------------------------+
8 rows in set (0.00 sec) mysql> show variables like 'collation_%';
+----------------------+-------------------+
| Variable_name | Value |
+----------------------+-------------------+
| collation_connection | utf8_general_ci |
| collation_database | latin1_swedish_ci |
| collation_server | latin1_swedish_ci |
+----------------------+-------------------+
3 rows in set (0.00 sec)

alter

mysql> show create database study_1;
+----------+-----------------------------------------------------------------+
| Database | Create Database |
+----------+-----------------------------------------------------------------+
| study_1 | CREATE DATABASE `study_1` /*!40100 DEFAULT CHARACTER SET gbk */ |
+----------+-----------------------------------------------------------------+
1 row in set (0.00 sec) mysql> alter database study_1 default character set 'utf8';
Query OK, 1 row affected (0.00 sec) mysql> show create database study_1;
+----------+------------------------------------------------------------------+
| Database | Create Database |
+----------+------------------------------------------------------------------+
| study_1 | CREATE DATABASE `study_1` /*!40100 DEFAULT CHARACTER SET utf8 */ |
+----------+------------------------------------------------------------------+
1 row in set (0.00 sec)

注意:这种情况是在数据库中没有数据修改的,如果数据库中有数据请慎用!

drop

mysql> drop database study_3;
Query OK, 0 rows affected (0.02 sec)

注意:删除前请确保数据库中没有重要数据。

表操作

create

直接创建

语法

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
(create_definition,...)
[table_options]
[partition_options]
  • TEMPORARY :创建临时表,创建在内存中,占用内存空间。

  • create_definition,... 可定义字段:字段名、类型和类型修饰符。也可定义键、约束或索引:PRIMARY KEY, UNIQUE KEY, FOREIGN KEY, CHECK 或者索引:{INDEX|KEY}

  • [table_options]:表的选项,下面列举了一些常用选项。

      ENGINE [=] engine_name:指定表的存储引擎,在使用此选项前需要先查看当前系统能支持的存储引擎,查询语句为SHOW ENGINES;通过查看DEFAULT所在位置可以看到系统默认引擎,而我们在创建表时不想使用系统默认引擎则在创建表的最后加上此选项就行了。而创建后我们还可以通过SHOW TABLE STATUS LIKE 'table_name'\G;语句来查看该表所使用的引擎。
    AUTO_INCREMENT [=] value :指定AUTO_INCREMENT的起始值。
    [DEFAULT] CHARACTER SET [=] charset_name :设定字符集。
    [DEFAULT] COLLATE [=] collation_name :指定排序规则。
    COMMENT [=] 'string' :增加表的注释信息。
    DELAY_KEY_WRITE [=] {0 | 1} :延迟键写入。
    ROW_FORMAT [=] {DEFAULT|DYNAMIC|FIXED|COMPRESSED|REDUNDANT|COMPACT} :表格式。
    TABLESPACE tablespace_name [STORAGE {DISK|MEMORY|DEFAULT}] :指定表空间。

举例

mysql> create table t5(Name varchar(30) NOT NULL,Age tinyint unsigned not null,Gender enum('F','M')NOT NULL,primary key(Name,Age))character set utf8 engine innodb;
Query OK, 0 rows affected (0.02 sec) mysql> desc t5;
+--------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+---------------------+------+-----+---------+-------+
| Name | varchar(30) | NO | PRI | NULL | |
| Age | tinyint(3) unsigned | NO | PRI | NULL | |
| Gender | enum('F','M') | NO | | NULL | |
+--------+---------------------+------+-----+---------+-------+
3 rows in set (0.00 sec) mysql> show create table t5\G;
*************************** 1. row ***************************
Table: t5
Create Table: CREATE TABLE `t5` (
`Name` varchar(30) NOT NULL,
`Age` tinyint(3) unsigned NOT NULL,
`Gender` enum('F','M') NOT NULL,
PRIMARY KEY (`Name`,`Age`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

复制表

语法

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
[(create_definition,...)]
[table_options]
[partition_options]
[IGNORE | REPLACE]
[AS] query_expression

举例

mysql> select * from t5;
+----------+-----+--------+
| Name | Age | Gender |
+----------+-----+--------+
| xiaoming | 20 | M |
+----------+-----+--------+
1 row in set (0.00 sec) mysql> desc t5;
+--------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+---------------------+------+-----+---------+-------+
| Name | varchar(30) | NO | PRI | NULL | |
| Age | tinyint(3) unsigned | NO | PRI | NULL | |
| Gender | enum('F','M') | NO | | NULL | |
+--------+---------------------+------+-----+---------+-------+
3 rows in set (0.00 sec) mysql> create table t7 select * from t5;
Query OK, 1 row affected (0.03 sec)
Records: 1 Duplicates: 0 Warnings: 0 mysql> desc t7;
+--------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+---------------------+------+-----+---------+-------+
| Name | varchar(30) | NO | | NULL | |
| Age | tinyint(3) unsigned | NO | | NULL | |
| Gender | enum('F','M') | NO | | NULL | |
+--------+---------------------+------+-----+---------+-------+
3 rows in set (0.00 sec) mysql> show create table t5\G
*************************** 1. row ***************************
Table: t5
Create Table: CREATE TABLE `t5` (
`Name` varchar(30) NOT NULL,
`Age` tinyint(3) unsigned NOT NULL,
`Gender` enum('F','M') NOT NULL,
PRIMARY KEY (`Name`,`Age`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec) mysql> show create table t7\G
*************************** 1. row ***************************
Table: t7
Create Table: CREATE TABLE `t7` (
`Name` varchar(30) CHARACTER SET utf8 NOT NULL,
`Age` tinyint(3) unsigned NOT NULL,
`Gender` enum('F','M') CHARACTER SET utf8 NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1 row in set (0.00 sec)

注意:这种方式的创建会复制表中的数据但是会丢失原表的属性。

复制表结构

语法

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
{ LIKE old_tbl_name | (LIKE old_tbl_name) }

举例

mysql> select * from t5;
+----------+-----+--------+
| Name | Age | Gender |
+----------+-----+--------+
| xiaoming | 20 | M |
+----------+-----+--------+
1 row in set (0.00 sec) mysql> desc t5;
+--------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+---------------------+------+-----+---------+-------+
| Name | varchar(30) | NO | PRI | NULL | |
| Age | tinyint(3) unsigned | NO | PRI | NULL | |
| Gender | enum('F','M') | NO | | NULL | |
+--------+---------------------+------+-----+---------+-------+
3 rows in set (0.00 sec) mysql> show create table t5\G
*************************** 1. row ***************************
Table: t5
Create Table: CREATE TABLE `t5` (
`Name` varchar(30) NOT NULL,
`Age` tinyint(3) unsigned NOT NULL,
`Gender` enum('F','M') NOT NULL,
PRIMARY KEY (`Name`,`Age`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec) mysql> create table t8 like t5;
Query OK, 0 rows affected (0.02 sec) mysql> select * from t8;
Empty set (0.00 sec) mysql> desc t8;
+--------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+---------------------+------+-----+---------+-------+
| Name | varchar(30) | NO | PRI | NULL | |
| Age | tinyint(3) unsigned | NO | PRI | NULL | |
| Gender | enum('F','M') | NO | | NULL | |
+--------+---------------------+------+-----+---------+-------+
3 rows in set (0.00 sec) mysql> show create table t8\G
*************************** 1. row ***************************
Table: t8
Create Table: CREATE TABLE `t8` (
`Name` varchar(30) NOT NULL,
`Age` tinyint(3) unsigned NOT NULL,
`Gender` enum('F','M') NOT NULL,
PRIMARY KEY (`Name`,`Age`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

rename

语法

RENAME TABLE tbl_name TO new_tbl_name
[, tbl_name2 TO new_tbl_name2] ...

举例

mysql> show create table vc\G
*************************** 1. row ***************************
Table: vc
Create Table: CREATE TABLE `vc` (
`v` varchar(4) DEFAULT NULL,
`c` char(4) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1
1 row in set (0.00 sec) mysql> rename table vc to t10;
Query OK, 0 rows affected (0.00 sec) mysql> show create table t10\G
*************************** 1. row ***************************
Table: t10
Create Table: CREATE TABLE `t10` (
`v` varchar(4) DEFAULT NULL,
`c` char(4) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1
1 row in set (0.00 sec)

insert

语法

INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name
[PARTITION (partition_name,...)]
[(col_name,...)]
{VALUES | VALUE} ({expr | DEFAULT},...),(...),...
[ ON DUPLICATE KEY UPDATE
col_name=expr
[, col_name=expr] ... ]

举例

mysql> desc t9;
+--------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+----------------+
| Id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| Gender | enum('M','F') | NO | | NULL | |
| Name | char(15) | NO | | NULL | |
| Info | char(20) | YES | | stu | |
+--------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec) mysql> insert into t9(Gender,Name,Info) value('M','xiaoming','student');
Query OK, 1 row affected (0.51 sec) mysql> insert into t9(Gender,Name,Info) value('F','xiaohong','student');
Query OK, 1 row affected (0.54 sec) mysql> insert into t9(Gender,Name) value('F','xiaoli');
Query OK, 1 row affected (0.54 sec) mysql> select * from t9;
+----+--------+----------+---------+
| Id | Gender | Name | Info |
+----+--------+----------+---------+
| 1 | M | xiaoming | student |
| 2 | F | xiaohong | student |
| 3 | F | xiaoli | stu |
+----+--------+----------+---------+
3 rows in set (0.00 sec) mysql> insert into t9(Gender,Name,Info) values('M','ouyangfeng','Teacher'),('F','xiaolongnv','Teacher');
Query OK, 2 rows affected (0.01 sec)
Records: 2 Duplicates: 0 Warnings: 0 mysql> select * from t9;
+----+--------+------------+---------+
| Id | Gender | Name | Info |
+----+--------+------------+---------+
| 1 | M | xiaoming | student |
| 2 | F | xiaohong | student |
| 3 | F | xiaoli | stu |
| 4 | M | ouyangfeng | Teacher |
| 5 | F | xiaolongnv | Teacher |
+----+--------+------------+---------+
5 rows in set (0.00 sec)

alter

语法

ALTER [ONLINE|OFFLINE] [IGNORE] TABLE tbl_name
[alter_specification [, alter_specification] ...]
[partition_options]

插入新字段

ADD [COLUMN] col_name column_definition  [FIRST | AFTER col_name ]

举例

mysql> desc t9;
+--------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+----------------+
| Id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| Gender | enum('M','F') | NO | | NULL | |
| Name | char(15) | NO | | NULL | |
| Info | char(20) | YES | | stu | |
+--------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec) mysql> alter table t9 add Age tinyint unsigned not null;
Query OK, 0 rows affected (0.04 sec)
Records: 0 Duplicates: 0 Warnings: 0 mysql> desc t9;
+--------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+---------------------+------+-----+---------+----------------+
| Id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| Gender | enum('M','F') | NO | | NULL | |
| Name | char(15) | NO | | NULL | |
| Info | char(20) | YES | | stu | |
| Age | tinyint(3) unsigned | NO | | NULL | |
+--------+---------------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

删除字段

语法

DROP [COLUMN] col_name

举例

mysql> alter table  t9 drop Age;
Query OK, 0 rows affected (1.13 sec)
Records: 0 Duplicates: 0 Warnings: 0 mysql> desc t9;
+--------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+----------------+
| Id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| Gender | enum('M','F') | NO | | NULL | |
| Name | char(15) | NO | | NULL | |
| Info | char(20) | YES | | stu | |
+--------+------------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

插入到指定位置

举例

mysql> alter table t9 add Age tinyint unsigned not null after Name;
Query OK, 0 rows affected (0.05 sec)
Records: 0 Duplicates: 0 Warnings: 0 mysql> desc t9;
+--------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+---------------------+------+-----+---------+----------------+
| Id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| Gender | enum('M','F') | NO | | NULL | |
| Name | char(15) | NO | | NULL | |
| Age | tinyint(3) unsigned | NO | | NULL | |
| Info | char(20) | YES | | stu | |
+--------+---------------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

修改字段

语法

CHANGE [COLUMN] old_col_name new_col_name column_definition  [FIRST|AFTER col_name]

举例

mysql> alter table t9 change Name  StuName char(20);
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0 mysql> desc t9;
+---------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+---------------------+------+-----+---------+----------------+
| Id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| Gender | enum('M','F') | NO | | NULL | |
| StuName | char(20) | YES | | NULL | |
| Age | tinyint(3) unsigned | NO | | NULL | |
| Info | char(20) | YES | | stu | |
+---------+---------------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

修改字段类型及属性

语法

MODIFY [COLUMN] col_name column_definition [FIRST | AFTER col_name]

举例

mysql> desc t9;
+---------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+---------------------+------+-----+---------+----------------+
| Id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| Gender | enum('M','F') | NO | | NULL | |
| StuName | char(20) | YES | | NULL | |
| Age | tinyint(3) unsigned | NO | | NULL | |
| Info | char(20) | YES | | stu | |
+---------+---------------------+------+-----+---------+----------------+
5 rows in set (0.00 sec) mysql> alter table t9 modify Gender enum('M','F') not null after StuName;
Query OK, 0 rows affected (0.58 sec)
Records: 0 Duplicates: 0 Warnings: 0 mysql> desc t9
-> ;
+---------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+---------------------+------+-----+---------+----------------+
| Id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| StuName | char(20) | YES | | NULL | |
| Gender | enum('M','F') | NO | | NULL | |
| Age | tinyint(3) unsigned | NO | | NULL | |
| Info | char(20) | YES | | stu | |
+---------+---------------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

修改约束、键或索引

语法

ADD {INDEX|KEY} [index_name]  [index_type] (index_col_name,...) [index_option]

举例

mysql> show indexes from t9;
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| t9 | 0 | PRIMARY | 1 | Id | A | 5 | NULL | NULL | | BTREE | | |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
1 row in set (0.00 sec) mysql> alter table t9 add index (Age);
Query OK, 0 rows affected (0.55 sec)
Records: 0 Duplicates: 0 Warnings: 0 mysql> show indexes from t9;
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| t9 | 0 | PRIMARY | 1 | Id | A | 5 | NULL | NULL | | BTREE | | |
| t9 | 1 | Age | 1 | Age | A | 2 | NULL | NULL | | BTREE | | |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
2 rows in set (0.00 sec) mysql> alter table t9 drop index Age;
Query OK, 0 rows affected (0.54 sec)
Records: 0 Duplicates: 0 Warnings: 0

修改表的存储引擎

举例

mysql> show table status like 'vc'\G
*************************** 1. row ***************************
Name: vc
Engine: InnoDB
Version: 10
Row_format: Compact
Rows: 1
Avg_row_length: 16384
Data_length: 16384
Max_data_length: 0
Index_length: 0
Data_free: 0
Auto_increment: NULL
Create_time: 2017-03-04 19:05:26
Update_time: NULL
Check_time: NULL
Collation: latin1_swedish_ci
Checksum: NULL
Create_options:
Comment:
1 row in set (0.00 sec) mysql> alter table vc engine=myisam;
Query OK, 1 row affected (0.56 sec)
Records: 1 Duplicates: 0 Warnings: 0 mysql> show table status like 'vc'\G
*************************** 1. row ***************************
Name: vc
Engine: MyISAM
Version: 10
Row_format: Dynamic
Rows: 1
Avg_row_length: 20
Data_length: 20
Max_data_length: 281474976710655
Index_length: 1024
Data_free: 0
Auto_increment: NULL
Create_time: 2017-03-05 01:51:47
Update_time: 2017-03-05 01:51:47
Check_time: NULL
Collation: latin1_swedish_ci
Checksum: NULL
Create_options:
Comment:
1 row in set (0.00 sec)

注意:实际使用中存储引擎是在表创建好就不会在修改的,一般都是使用InnoDB存储引擎。

转换字符集

把表默认的字符集和所有字符列(CHAR,VARCHAR,TEXT)改为新的字符集:
语法

ALTER TABLE tbl_name CONVERT TO CHARACTER SET character_name [COLLATE ...]

举例

mysql> show full columns from t9;
+---------+---------------------+-------------------+------+-----+---------+----------------+---------------------------------+---------+
| Field | Type | Collation | Null | Key | Default | Extra | Privileges | Comment |
+---------+---------------------+-------------------+------+-----+---------+----------------+---------------------------------+---------+
| Id | int(10) unsigned | NULL | NO | PRI | NULL | auto_increment | select,insert,update,references | |
| StuName | char(20) | latin1_swedish_ci | YES | | NULL | | select,insert,update,references | |
| Gender | enum('M','F') | latin1_swedish_ci | NO | | NULL | | select,insert,update,references | |
| Age | tinyint(3) unsigned | NULL | NO | MUL | NULL | | select,insert,update,references | |
| Info | char(20) | latin1_swedish_ci | YES | | stu | | select,insert,update,references | |
+---------+---------------------+-------------------+------+-----+---------+----------------+---------------------------------+---------+
5 rows in set (0.00 sec) mysql> show create table t9\G
*************************** 1. row ***************************
Table: t9
Create Table: CREATE TABLE `t9` (
`Id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`StuName` char(20) DEFAULT NULL,
`Gender` enum('M','F') NOT NULL,
`Age` tinyint(3) unsigned NOT NULL,
`Info` char(20) DEFAULT 'stu',
PRIMARY KEY (`Id`),
KEY `Age` (`Age`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1
1 row in set (0.00 sec) mysql> alter table t9 convert to character set utf8 collate utf8_general_ci;
Query OK, 5 rows affected (0.58 sec)
Records: 5 Duplicates: 0 Warnings: 0 mysql> show full columns from t9;
+---------+---------------------+-----------------+------+-----+---------+----------------+---------------------------------+---------+
| Field | Type | Collation | Null | Key | Default | Extra | Privileges | Comment |
+---------+---------------------+-----------------+------+-----+---------+----------------+---------------------------------+---------+
| Id | int(10) unsigned | NULL | NO | PRI | NULL | auto_increment | select,insert,update,references | |
| StuName | char(20) | utf8_general_ci | YES | | NULL | | select,insert,update,references | |
| Gender | enum('M','F') | utf8_general_ci | NO | | NULL | | select,insert,update,references | |
| Age | tinyint(3) unsigned | NULL | NO | | NULL | | select,insert,update,references | |
| Info | char(20) | utf8_general_ci | YES | | stu | | select,insert,update,references | |
+---------+---------------------+-----------------+------+-----+---------+----------------+---------------------------------+---------+
5 rows in set (0.00 sec) mysql> show create table t9\G
*************************** 1. row ***************************
Table: t9
Create Table: CREATE TABLE `t9` (
`Id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`StuName` char(20) DEFAULT NULL,
`Gender` enum('M','F') NOT NULL,
`Age` tinyint(3) unsigned NOT NULL,
`Info` char(20) DEFAULT 'stu',
PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

只是修改表的默认字符集

语法

ALTER TABLE tbl_name DEFAULT CHARACTER SET character_name [COLLATE...];

举例

mysql> show full columns from t6;
+--------+---------------------+-------------------+------+-----+---------+-------+---------------------------------+---------+
| Field | Type | Collation | Null | Key | Default | Extra | Privileges | Comment |
+--------+---------------------+-------------------+------+-----+---------+-------+---------------------------------+---------+
| Name | varchar(30) | latin1_swedish_ci | NO | PRI | NULL | | select,insert,update,references | |
| Age | tinyint(3) unsigned | NULL | NO | PRI | NULL | | select,insert,update,references | |
| Gender | enum('F','M') | latin1_swedish_ci | NO | | NULL | | select,insert,update,references | |
+--------+---------------------+-------------------+------+-----+---------+-------+---------------------------------+---------+
3 rows in set (0.00 sec) mysql> show create table t6\G
*************************** 1. row ***************************
Table: t6
Create Table: CREATE TABLE `t6` (
`Name` varchar(30) NOT NULL,
`Age` tinyint(3) unsigned NOT NULL,
`Gender` enum('F','M') NOT NULL,
PRIMARY KEY (`Name`,`Age`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1 row in set (0.00 sec) mysql> alter table t6 default character set utf8 collate utf8_general_ci;
Query OK, 0 rows affected (0.58 sec)
Records: 0 Duplicates: 0 Warnings: 0 mysql> show create table t6\G
*************************** 1. row ***************************
Table: t6
Create Table: CREATE TABLE `t6` (
`Name` varchar(30) CHARACTER SET latin1 NOT NULL,
`Age` tinyint(3) unsigned NOT NULL,
`Gender` enum('F','M') CHARACTER SET latin1 NOT NULL,
PRIMARY KEY (`Name`,`Age`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec) mysql> show full columns from t6;
+--------+---------------------+-------------------+------+-----+---------+-------+---------------------------------+---------+
| Field | Type | Collation | Null | Key | Default | Extra | Privileges | Comment |
+--------+---------------------+-------------------+------+-----+---------+-------+---------------------------------+---------+
| Name | varchar(30) | latin1_swedish_ci | NO | PRI | NULL | | select,insert,update,references | |
| Age | tinyint(3) unsigned | NULL | NO | PRI | NULL | | select,insert,update,references | |
| Gender | enum('F','M') | latin1_swedish_ci | NO | | NULL | | select,insert,update,references | |
+--------+---------------------+-------------------+------+-----+---------+-------+---------------------------------+---------+
3 rows in set (0.00 sec)

修改字段的字符集

语法

ALTER TABLE tbl_name CHANGE c_name c_name CHARACTER SET character_name [COLLATE ...];

举例

mysql> alter table t6 change Name Name varchar(30) character set utf8 not null collate utf8_general_ci;
Query OK, 1 row affected (0.04 sec)
Records: 1 Duplicates: 0 Warnings: 0 mysql> show full columns from t6;
+--------+---------------------+-------------------+------+-----+---------+-------+---------------------------------+---------+
| Field | Type | Collation | Null | Key | Default | Extra | Privileges | Comment |
+--------+---------------------+-------------------+------+-----+---------+-------+---------------------------------+---------+
| Name | varchar(30) | utf8_general_ci | NO | PRI | NULL | | select,insert,update,references | |
| Age | tinyint(3) unsigned | NULL | NO | PRI | NULL | | select,insert,update,references | |
| Gender | enum('F','M') | latin1_swedish_ci | NO | | NULL | | select,insert,update,references | |
+--------+---------------------+-------------------+------+-----+---------+-------+---------------------------------+---------+
3 rows in set (0.01 sec) mysql> show create table t6\G
*************************** 1. row ***************************
Table: t6
Create Table: CREATE TABLE `t6` (
`Name` varchar(30) NOT NULL,
`Age` tinyint(3) unsigned NOT NULL,
`Gender` enum('F','M') CHARACTER SET latin1 NOT NULL,
PRIMARY KEY (`Name`,`Age`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec) mysql> alter table t6 change Gender Gender enum('F','M') character set utf8 not null collate utf8_general_ci;
Query OK, 1 row affected (0.04 sec)
Records: 1 Duplicates: 0 Warnings: 0 mysql> show create table t6\G
*************************** 1. row ***************************
Table: t6
Create Table: CREATE TABLE `t6` (
`Name` varchar(30) NOT NULL,
`Age` tinyint(3) unsigned NOT NULL,
`Gender` enum('F','M') NOT NULL,
PRIMARY KEY (`Name`,`Age`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec) mysql> show full columns from t6;
+--------+---------------------+-----------------+------+-----+---------+-------+---------------------------------+---------+
| Field | Type | Collation | Null | Key | Default | Extra | Privileges | Comment |
+--------+---------------------+-----------------+------+-----+---------+-------+---------------------------------+---------+
| Name | varchar(30) | utf8_general_ci | NO | PRI | NULL | | select,insert,update,references | |
| Age | tinyint(3) unsigned | NULL | NO | PRI | NULL | | select,insert,update,references | |
| Gender | enum('F','M') | utf8_general_ci | NO | | NULL | | select,insert,update,references | |
+--------+---------------------+-----------------+------+-----+---------+-------+---------------------------------+---------+
3 rows in set (0.00 sec)

select

语法

SELECT
[ALL | DISTINCT | DISTINCTROW ]
[HIGH_PRIORITY]
[STRAIGHT_JOIN]
[SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
[SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
select_expr [, select_expr ...]
[FROM table_references
[PARTITION partition_list]
[WHERE where_condition]
[GROUP BY {col_name | expr | position}
[ASC | DESC], ... [WITH ROLLUP]]
[HAVING where_condition]
[ORDER BY {col_name | expr | position}
[ASC | DESC], ...]
[LIMIT {[offset,] row_count | row_count OFFSET offset}]
[PROCEDURE procedure_name(argument_list)]
[INTO OUTFILE 'file_name'
[CHARACTER SET charset_name]
export_options
| INTO DUMPFILE 'file_name'
| INTO var_name [, var_name]]
[FOR UPDATE | LOCK IN SHARE MODE]]

举例

mysql> select * from t9;
+----+------------+--------+--------+-----+---------+
| Id | StuName | Result | Gender | Age | Info |
+----+------------+--------+--------+-----+---------+
| 1 | xiaoming | 66 | M | 20 | stu |
| 2 | xiaohong | 69 | F | 17 | stu |
| 3 | xiaoli | 10 | F | 15 | stu |
| 4 | ouyangfeng | 88 | M | 17 | Teacher |
| 5 | xiaolongnv | 96 | F | 25 | Teacher |
| 6 | guojing | 59 | M | 35 | stu |
+----+------------+--------+--------+-----+---------+
6 rows in set (0.00 sec) mysql> desc t9;
+---------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+---------------------+------+-----+---------+----------------+
| Id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| StuName | char(20) | YES | | NULL | |
| Result | tinyint(3) unsigned | NO | | NULL | |
| Gender | enum('M','F') | NO | | NULL | |
| Age | tinyint(3) unsigned | NO | | NULL | |
| Info | char(20) | YES | | stu | |
+---------+---------------------+------+-----+---------+----------------+
6 rows in set (0.00 sec)

查询年龄在20~30之间的人:

mysql> select StuName,Age from t9 where Age between 20 and 30;
+------------+-----+
| StuName | Age |
+------------+-----+
| xiaoming | 20 |
| xiaolongnv | 25 |
+------------+-----+
2 rows in set (0.02 sec)

年龄大于20的人:

mysql> select StuName,Age from t9 where Age > 20;
+------------+-----+
| StuName | Age |
+------------+-----+
| xiaolongnv | 25 |
| guojing | 35 |
+------------+-----+
2 rows in set (0.01 sec)

查看年龄是20,21,22的人:

mysql> select StuName,Age from t9 where Age in(20,21,22);
+----------+-----+
| StuName | Age |
+----------+-----+
| xiaoming | 20 |
+----------+-----+
1 row in set (0.00 sec)

查看StuName以g开头的行:

mysql> select StuName from t9 where StuName like 'g%';
+---------+
| StuName |
+---------+
| guojing |
+---------+
1 row in set (0.00 sec)

查看StuName内容是null/not null 的内容:

mysql> select StuName from t9 where StuName is null;
Empty set (0.00 sec) mysql> select StuName from t9 where StuName is not null;
+------------+
| StuName |
+------------+
| xiaoming |
| xiaohong |
| xiaoli |
| ouyangfeng |
| xiaolongnv |
| guojing |
+------------+
6 rows in set (0.00 sec)

查看年龄大于30且是男人:

mysql> select StuName,Age,Gender from t9 where Age > 30 and Gender = 'M';
+---------+-----+--------+
| StuName | Age | Gender |
+---------+-----+--------+
| guojing | 35 | M |
+---------+-----+--------+
1 row in set (0.00 sec)

查看成绩大于60并且性别是F的人以降序输出:

mysql> select StuName,Result from t9 where Result>60 and Gender = 'F' order by Result desc;
+------------+--------+
| StuName | Result |
+------------+--------+
| xiaolongnv | 96 |
| xiaohong | 69 |
+------------+--------+
2 rows in set (0.00 sec)

根据性别分组并求和:

mysql> select Gender,sum(Age) from t9 group by gender;
+--------+----------+
| Gender | sum(Age) |
+--------+----------+
| M | 72 |
| F | 57 |
+--------+----------+
2 rows in set (0.00 sec)

查看t9表中的前两个:

mysql> select * from t9 limit 2;
+----+----------+--------+--------+-----+------+
| Id | StuName | Result | Gender | Age | Info |
+----+----------+--------+--------+-----+------+
| 1 | xiaoming | 66 | M | 20 | stu |
| 2 | xiaohong | 69 | F | 17 | stu |
+----+----------+--------+--------+-----+------+
2 rows in set (0.00 sec)

查询t9表跳过前两行后在显示三行:

mysql> select * from t9 limit 2,3;
+----+------------+--------+--------+-----+---------+
| Id | StuName | Result | Gender | Age | Info |
+----+------------+--------+--------+-----+---------+
| 3 | xiaoli | 10 | F | 15 | stu |
| 4 | ouyangfeng | 88 | M | 17 | Teacher |
| 5 | xiaolongnv | 96 | F | 25 | Teacher |
+----+------------+--------+--------+-----+---------+
3 rows in set (0.00 sec)

多表查询学习

update

单表

语法

UPDATE [LOW_PRIORITY] [IGNORE] table_reference
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]

UPDATE语法可以用新值更新原有表行中的各列。SET子句指示要修改哪些列和要给予哪些值。WHERE子句指定应更新哪些行。如果没有WHERE子句,则更新所有的行。如果指定了ORDER BY子句,则按照被指定的顺序对行进行更新。LIMIT子句用于给定一个限值,限制可以被更新的行的数目。

举例
修改表中StuName中xiaoli字段为lixiaoyao:

mysql> select * from t9;
+----+------------+--------+--------+-----+---------+
| Id | StuName | Result | Gender | Age | Info |
+----+------------+--------+--------+-----+---------+
| 1 | xiaoming | 66 | M | 20 | stu |
| 2 | xiaohong | 69 | F | 17 | stu |
| 3 | xiaoli | 10 | F | 15 | stu |
| 4 | ouyangfeng | 88 | M | 17 | Teacher |
| 5 | xiaolongnv | 96 | F | 25 | Teacher |
| 6 | guojing | 59 | M | 35 | stu |
+----+------------+--------+--------+-----+---------+
6 rows in set (0.00 sec) mysql> update t9 set StuName = 'lixiaoyao' where Id=3;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0 mysql> select * from t9;
+----+------------+--------+--------+-----+---------+
| Id | StuName | Result | Gender | Age | Info |
+----+------------+--------+--------+-----+---------+
| 1 | xiaoming | 66 | M | 20 | stu |
| 2 | xiaohong | 69 | F | 17 | stu |
| 3 | lixiaoyao | 10 | F | 15 | stu |
| 4 | ouyangfeng | 88 | M | 17 | Teacher |
| 5 | xiaolongnv | 96 | F | 25 | Teacher |
| 6 | guojing | 59 | M | 35 | stu |
+----+------------+--------+--------+-----+---------+
6 rows in set (0.00 sec)

修改root@localhost用户的密码:

mysql> update mysql.user set password=password('redhat') where user='root' and host='localhost';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0

多表

语法

UPDATE [LOW_PRIORITY] [IGNORE] table_references
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]

delete

在MySQL中有两种方法可以删除数据,一种是DELETE语句,另一种是TRUNCATE TABLE语句。DELETE语句可以通过WHERE对要删除的记录进行选择。而使用TRUNCATE TABLE将删除表中的所有记录。因此,DELETE语句更灵活。

单表

语法

DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM tbl_name
[PARTITION (partition_name,...)]
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]

举例

mysql> select * from t11;
+----+------------+--------+--------+-----+---------+
| Id | StuName | Result | Gender | Age | Info |
+----+------------+--------+--------+-----+---------+
| 1 | xiaoming | 66 | M | 20 | stu |
| 2 | xiaohong | 69 | F | 17 | stu |
| 3 | lixiaoyao | 10 | F | 15 | stu |
| 4 | ouyangfeng | 88 | M | 17 | Teacher |
| 5 | xiaolongnv | 96 | F | 25 | Teacher |
| 6 | guojing | 59 | M | 35 | stu |
+----+------------+--------+--------+-----+---------+
6 rows in set (0.00 sec) mysql> delete from t11 where StuName = 'xiaohong';
Query OK, 1 row affected (0.53 sec) mysql> select * from t11;
+----+------------+--------+--------+-----+---------+
| Id | StuName | Result | Gender | Age | Info |
+----+------------+--------+--------+-----+---------+
| 1 | xiaoming | 66 | M | 20 | stu |
| 3 | lixiaoyao | 10 | F | 15 | stu |
| 4 | ouyangfeng | 88 | M | 17 | Teacher |
| 5 | xiaolongnv | 96 | F | 25 | Teacher |
| 6 | guojing | 59 | M | 35 | stu |
+----+------------+--------+--------+-----+---------+
5 rows in set (0.00 sec) mysql> delete from t11 where StuName like 'x%';
Query OK, 2 rows affected (0.55 sec) mysql> select * from t11;
+----+------------+--------+--------+-----+---------+
| Id | StuName | Result | Gender | Age | Info |
+----+------------+--------+--------+-----+---------+
| 3 | lixiaoyao | 10 | F | 15 | stu |
| 4 | ouyangfeng | 88 | M | 17 | Teacher |
| 6 | guojing | 59 | M | 35 | stu |
+----+------------+--------+--------+-----+---------+
3 rows in set (0.00 sec) mysql> delete from t11 ;
Query OK, 3 rows affected (0.01 sec) mysql> select * from t11;
Empty set (0.00 sec)

注意事项:从语法结构中,我们就可以看出,和 update 语法一样,我们是可以省略 where 子句的。不过这是一个很危险的行为。因为如果不指定 where 子句,delete 将删除表中所有的记录,而且是立即删除,即使你想哭都没有地方,也没有时间,因为你需要马上和主管承认错误,并且立即找出MySQL日志,来回滚记录。不过一旦你有过一次这样的经历,我相信这一定是印象深刻的。

SQL语句.md的更多相关文章

  1. MySQL的常用SQL语句.md

    修改密码 这是常见的大家一般都要用的 首先     安装成功了打开cmd --> mysql -u root -p -->输入你的密码     修改mysql root用户密码    格式 ...

  2. 向已写好的多行插入sql语句中添加字段和值

    #region 添加支款方式--向已写好的多行插入sql语句中添加字段和值 public int A_ZhifuFS(int diqu) { ; string strData = @"SEL ...

  3. Mysql数据库里面的String类型依照数字来排序以及按时间排序的sql语句

    今天做项目的时候,遇到个小小的问题,在数据库中查询的时候,要用String类型的ID进行一下排序!(注:ID字段为 varchar 类型) 解决的方法: 如: SELECT * FROM  Stude ...

  4. java执行多条SQL语句

    一次执行多条SQL的技术要点如下: DatabaseMetaData接口是描述有关数据库的整体综合信息,由于DatabaseMetaData是接口,所以没有构造方法,故不能使用new来创建Databa ...

  5. [Beego模型] 四、使用SQL语句进行查询

    [Beego模型] 一.ORM 使用方法 [Beego模型] 二.CRUD 操作 [Beego模型] 三.高级查询 [Beego模型] 四.使用SQL语句进行查询 [Beego模型] 五.构造查询 [ ...

  6. mysql按年度、季度、月度、周、日统计查询的sql语句

    本文介绍一些mysql中用于查询的sql语句,包括按年度.季度.月度.周.日统计查询等,有需要的朋友,可以参考下. 一.年度查询 查询 本年度的数据   SELECT * FROM blog_arti ...

  7. MSSQL注入常用SQL语句整理

    很多情况下使用工具对mssql注入并不完善,所以我们就需要手工注入,一下是本人收集的一些mssql的sql语句. 手工MSSQL注入常用SQL语句 and exists (select * from ...

  8. [转帖]PG语法解剖--基本sql语句用法入门

    PG语法解剖--基本sql语句用法入门 https://www.toutiao.com/i6710897833953722894/ COPY 命令挺好的 需要学习一下. 原创 波波说运维 2019-0 ...

  9. mysql学习之 sql语句的技巧及优化

    一.sql中使用正则表达式 select name,email from user where email Regexp "@163[.,]com$"; sql语句中使用Regex ...

随机推荐

  1. Android Studio 1.1.0汉化初步出炉!

    我找到去年12月国人汉化的版本,然后迁移上来的.实测支持Android window最新版(1.1.0) 项目分4部分:1压缩好的:2文本分析器:3原生的语言包:4原版语言包备份 现在一些新增的项目没 ...

  2. 请整体描述Java异常体系

    java把异常当做对象来处理,并定义一个基类Throwable作为所有异常的超类.在java API中已经定义了许多异常的类,这些异常分为两大类,错误Error和异常Exception.其中异常Exc ...

  3. 《码出高效 Java开发手册》第七章 并发与多线程

    码云: https://gitee.com/forxiaoming/JavaBaseCode/blob/master/EasyCoding/src/concurrency/multithreading ...

  4. 1 springboot创建项目

    文章采用idea工具进行springboot项目创建 1点击 New Project 选择[Spring Initializr] 选择Jdk版本其他默认即可 点击Next 2添加项目信息 文章即使用默 ...

  5. Vue 中的 v-cloak 解读

    v-cloak 的作用和用法 用法: 这个指令保持在元素上直到关联实例结束编译.和 CSS 规则如 [v-cloak] { display: none } 一起用时,这个指令可以隐藏未编译的 Must ...

  6. mysql索引类型normal,unique,full text的区别

    normal:表示普通索引 unique:表示唯一的,不允许重复的索引,如果该字段信息保证不会重复例如身份证号用作索引时,可设置为unique full textl: 表示 全文搜索的索引. FULL ...

  7. 通过UA判断,对滚动条样式进行不同的操作

    浏览器滚动条的默认样式比较丑,有些情况下,又不能直接overflow:hidden掉. 本文阐述如何通过 document.styleSheets[0].insertRule 简单的实现pc端和移动端 ...

  8. BZOJ3672: [Noi2014]购票(dp 斜率优化 点分治 二分 凸包)

    题意 题目链接 Sol 介绍一种神奇的点分治的做法 啥?这都有根树了怎么点分治?? 嘿嘿,这道题的点分治不同于一般的点分治.正常的点分治思路大概是先统计过重心的,再递归下去 实际上一般的点分治与统计顺 ...

  9. apply与call简单用法以及判断数组的坑

    1 typeof 和 instanceof var array = [];平时如果判断一个对象是否为数组,可能你会用 typeof array,但是输出为“object”. typeof 一般只能返回 ...

  10. Spring Boot—19Cache

    pom.xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId> ...