mysql基本操作

库操作

1、数据库命名规则

可以由字母、数字、下划线、@、#、$
区分大小写
唯一性
不能使用关键字如 create select
不能单独使用数字
最长128位

表操作

复制表

1、复制表结构和记录

mysql> create table tuser select host,user from mysql.user;

2、只复制表结构

mysql> create table t2 select host,user from mysql.user where 1>5 //条件为假,查不到任何记录

删除表

drop table 表名

日期类型

year

mysql> create table t8 (bron_year year(9)); #无论year指定何种宽度,最后都默认是year(4)

mysql> insert into t8 values();

mysql> insert into t8 values
    -> (1990),
    -> (2008),
    -> (2018);

mysql> select bron_year,char_length(bron_year) from t8;

+-----------+------------------------+
| bron_year | char_length(bron_year) |
+-----------+------------------------+
|      NULL |                   NULL |
|      1990 |                      4 |
|      2008 |                      4 |
|      2018 |                      4 |
+-----------+------------------------+
4 rows in set (0.00 sec)

date,time,datetime

mysql> create table t9(d date, t time, dt datetime);

mysql> insert into t9 values(now(),now(),now());

mysql> desc t9;

+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| d     | date     | YES  |     | NULL    |       |
| t     | time     | YES  |     | NULL    |       |
| dt    | datetime | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+


mysql> select * from t9;

+------------+----------+---------------------+
| d          | t        | dt                  |
+------------+----------+---------------------+
| 2018-03-10 | 21:38:37 | 2018-03-10 21:38:37 |
+------------+----------+---------------------+

timestamp

create table t10(time timestamp);

mysql> desc t10;

+-------+-----------+------+-----+-------------------+-----------------------------+
| Field | Type      | Null | Key | Default           | Extra                       |
+-------+-----------+------+-----+-------------------+-----------------------------+
| time  | timestamp | NO   |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+-------+-----------+------+-----+-------------------+-----------------------------+

mysql> insert into t10 values();

mysql> insert into t10 values(null);

mysql> insert into t10 values(now());

mysql> select * from t10;

+---------------------+
| time                |
+---------------------+
| 2018-03-10 21:44:34 |
| 2018-03-10 21:44:39 |
| 2018-03-10 21:45:46 |
+---------------------+

注意

1. 单独插入时间时,需要以字符串的形式,按照对应的格式插入
2. 插入年份时,尽量使用4位值
3. 插入两位年份时,<=69,以20开头,比如50,  结果2050      
                >=70,以19开头,比如71,结果1971
                
                
mysql> create table t11(y year); 
                                 
mysql> insert into t11 values    
    -> (50),                     
    -> (79);                     

mysql> select *from t11;         
+------+                         
| y    |                         
+------+                         
| 2050 |                         
| 1979 |                         
+------+                         

综合练习

MariaDB [db1]> create table student(
    -> id int,
    -> name varchar(20),
    -> born_year year,
    -> birth date,
    -> class_time time,
    -> reg_time datetime);

MariaDB [db1]> insert into student values
    -> (1,'alex',"1995","1995-11-11","11:11:11","2017-11-11 11:11:11"),
    -> (2,'egon',"1997","1997-12-12","12:12:12","2017-12-12 12:12:12"),
    -> (3,'wsb',"1998","1998-01-01","13:13:13","2017-01-01 13:13:13");

MariaDB [db1]> select * from student;
+------+------+-----------+------------+------------+---------------------+
| id   | name | born_year | birth      | class_time | reg_time            |
+------+------+-----------+------------+------------+---------------------+
|    1 | alex |      1995 | 1995-11-11 | 11:11:11   | 2017-11-11 11:11:11 |
|    2 | egon |      1997 | 1997-12-12 | 12:12:12   | 2017-12-12 12:12:12 |
|    3 | wsb  |      1998 | 1998-01-01 | 13:13:13   | 2017-01-01 13:13:13 |
+------+------+-----------+------------+------------+---------------------+

datetime与timestamp的区别

实际应用的很多场景中,MySQL的这两种日期类型都能够满足我们的需要,存储精度都为秒,但在某些情况下,会展现出他们各自的优劣。
下面就来总结一下两种日期类型的区别。

1.DATETIME的日期范围是1001——9999年,TIMESTAMP的时间范围是1970——2038年。

2.DATETIME存储时间与时区无关,TIMESTAMP存储时间与时区有关,显示的值也依赖于时区。在mysql服务器,
操作系统以及客户端连接都有时区的设置。

3.DATETIME使用8字节的存储空间,TIMESTAMP的存储空间为4字节。因此,TIMESTAMP比DATETIME的空间利用率更高。

4.DATETIME的默认值为null;TIMESTAMP的字段默认不为空(not null),默认值为当前时间(CURRENT_TIMESTAMP),
如果不做特殊处理,并且update语句中没有指定该列的更新值,则默认更新为当前时间。

枚举类型与集合类型

字段的值只能在给定范围中选择,如单选框,多选框

enum 单选题 只能在给定的范围内选一个值

set 多选题 在给定的范围内可以选择一个或一个以上的值(爱好1,爱好2,爱好3...)

mysql> create table choice(
    -> single_choice enum('a','b','c','d'),
    -> mul_choice set('a','b','c','d'));
    
mysql> desc choice;

+---------------+-----------------------+------+-----+---------+-------+
| Field         | Type                  | Null | Key | Default | Extra |
+---------------+-----------------------+------+-----+---------+-------+
| single_choice | enum('a','b','c','d') | YES  |     | NULL    |       |
| mul_choice    | set('a','b','c','d')  | YES  |     | NULL    |       |
+---------------+-----------------------+------+-----+---------+-------+

mysql> insert into choice values('a', 'a,b,c');

mysql> select * from choice;

+---------------+------------+
| single_choice | mul_choice |
+---------------+------------+
| a             | a,b,c      |
+---------------+------------+

完整性约束

1、介绍

约束条件与数据类型的宽度一样,都是可选参数

作用:用于保证数据的完整性和一致性

PRIMARY KEY (PK)    标识该字段为该表的主键,可以唯一的标识记录
FOREIGN KEY (FK)    标识该字段为该表的外键
NOT NULL    标识该字段不能为空
UNIQUE KEY (UK)    标识该字段的值是唯一的
AUTO_INCREMENT    标识该字段的值自动增长(整数类型,而且为主键)
DEFAULT    为该字段设置默认值

UNSIGNED 无符号
ZEROFILL 使用0填充

说明

1. 是否允许为空,默认NULL,可设置NOT NULL,字段不允许为空,必须赋值
2. 字段是否有默认值,缺省的默认值是NULL,如果插入记录时不给字段赋值,此字段使用默认值
sex enum('male','female') not null default 'male'
age int unsigned NOT NULL default 20 必须为正值(无符号) 不允许为空 默认是20
3. 是否是key
主键 primary key
外键 foreign key
索引 (index,unique...)
4、删除某字段唯一
ALTER TABLE 表 DROP  INDEX 字段;
如:
alter table score drop index sid;
练习
mysql> create table student(
    -> name varchar(16) not null,
    -> age int(3) unsigned not null default 18,
    -> sex enum('male', 'female') not null default 'male',
    -> hobby set('music','run', 'girl') not null default 'girl');


mysql> desc student;

+-------+---------------------------+------+-----+---------+-------+
| Field | Type                      | Null | Key | Default | Extra |
+-------+---------------------------+------+-----+---------+-------+
| name  | varchar(16)               | NO   |     | NULL    |       |
| age   | int(3) unsigned           | NO   |     | 18      |       |
| sex   | enum('male','female')     | NO   |     | male    |       |
| hobby | set('music','run','girl') | NO   |     | girl    |       |
+-------+---------------------------+------+-----+---------+-------+

mysql> insert into student values();

mysql> insert into student(name) values('alex');

mysql> select * from student;

+------+-----+------+-------+
| name | age | sex  | hobby |
+------+-----+------+-------+
|      |  18 | male | girl  |
| alex |  18 | male | girl  |
+------+-----+------+-------+

unique

单列唯一
	#方式一
	create table department(
		id int unique,
		name char(10) unique
	);
	#方式二:
	create table department(
		id int,
		name char(10),
		unique(id),
		unique(name)
	);




	insert into department values
	(1,'IT'),
	(2,'Sale');


联合唯一
create table services(
	id int,
	ip char(15),
	port int,
	unique(id),
	unique(ip,port)
);



insert into services values
(1,'192.168.11.10',80),
(2,'192.168.11.10',81),
(3,'192.168.11.13',80);




insert into services values
(4,'192.168.11.10',80);

primary key


# 单列主键
create table t17(
	id int primary key,
	name char(16)
);



insert into t17 values
(1,'egon'),
(2,'alex');

insert into t17 values
(2,'wxx');

insert into t17(name) values
('wxx');

create table t18(
	id int not null unique,
	name char(16)
);



# 复合主键
create table t19(
	ip char(15),
	port int,
	primary key(ip,port)
);


insert into t19 values
('1.1.1.1',80),
('1.1.1.1',81);

primary key

primary key字段的值不为空且唯一

一个表中可以:

单列做主键
多列做主键(复合主键)

但一个表内只能有一个主键primary key

单列做主键
#方法一:not null+unique

mysql> create table t6( id int not null unique, name varchar(16) );
Query OK, 0 rows affected (0.01 sec)

mysql> desc t6;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | NO   | PRI | NULL    |       |
| name  | varchar(16) | YES  |     | NULL    |       |

#方法二:在某一个字段后用primary key

mysql> create table t3(id int not null primary key);
Query OK, 0 rows affected (0.03 sec)

mysql> desc t3;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | NO   | PRI | NULL    |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.02 sec)

#方法三:在所有字段后单独定义primary key

mysql> create table t4(
    -> id int not null,
    -> name varchar(16),
    -> primary key(id)
    -> );
Query OK, 0 rows affected (0.02 sec)

mysql> desc t4;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | NO   | PRI | NULL    |       |
| name  | varchar(16) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

多列做主键
create table service(
ip varchar(15),
port char(5),
service_name varchar(10) not null,
primary key(ip,port)
);


mysql> desc service;
+--------------+-------------+------+-----+---------+-------+
| Field        | Type        | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| ip           | varchar(15) | NO   | PRI | NULL    |       |
| port         | char(5)     | NO   | PRI | NULL    |       |
| service_name | varchar(10) | NO   |     | NULL    |       |
+--------------+-------------+------+-----+---------+-------+
rows in set (0.00 sec)

mysql> insert into service values
    -> ('172.16.45.10','3306','mysqld'),
    -> ('172.16.45.11','3306','mariadb')
    -> ;
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

auto_increment

约束字段为自动增长,被约束的字段必须同时被key约束

create table student(
id int primary key auto_increment,
name varchar(20),
sex enum('male','female') default 'male'
);

注意

auto_increment时增加新内容

清空表:

delete from t1; #如果有自增id,新增的数据,仍然是以删除前的最后一样作为起始。

truncate table t1;数据量大,删除速度比上一条快,且直接从零开始,

了解

show variables like 'auto_inc%';

	#步长:
	auto_increment_increment默认为1
	#起始偏移量
	auto_increment_offset默认1
	
	#设置步长
	set session auto_increment_increment=5;
	set global auto_increment_increment=5;
	
	#设置起始偏移量
	set global auto_increment_offset=3;
	强调:起始偏移量<=步长
	

foreign key

用来在两个的数据之间建立连接,它可以是一列或者多列。一个表可以有一个或者多个外键。
外键对应的是参照完整性,一个表的外键可以为空,若不为控制,则每一个外键值必须等于另一个表中主键的某一个值。

外键的作用是保持数据一致性。

constraint 外键约束名 foreign key(外键名) references 依赖表(依赖字段) ;

在student表中增加一个名为class_id的外键,外键引用class表的cid字段;

create table student
(sid int not null unique,
class_id int,
constraint con_cid foreign key(class_id) references class(cid)
);
原文地址:https://www.cnblogs.com/Jason-lin/p/8552734.html