MySQL的基础命令

本文系统介绍MySQL基础操作命令及各类语法约束。涵盖数据库/表的创建、查看、删除、修改等CRUD操作,包括通配符使用、DESC查看结构、INSERT写入、ALTER TABLE列管理等;重点解析非空、默认值、主键、唯一键、外键、检查约束的定义、作用与删除方法,并强调MySQL 8.0.16+对CHECK约束的强制生效特性。

MySQL操作命令

优化配置

因为正常启动MySQL过于繁琐,所以使用前建议配置启动脚本

[root@server mysql]# vim /usr/lib/systemd/system/mysqld.service
[Unit]
Description=MySQL Server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=notify
User=mysql
Group=mysql
ExecStart=/usr/local/mysql/bin/mysqld --defaults-file=/etc/my.cnf
LimitNOFILE=65535
LimitNPROC=65535
Restart=on-failure
RestartPreventExitStatus=1
TimeoutSec=0

[Install]
WantedBy=multi-user.target
[root@master mysql]# systemctl daemon-reload
[root@master mysql]# systemctl enable --now mysqld.service

配置完成后就可以所以systemctl开启MySQL服务端

[root@master mysql]# systemctl start mysqld.service

登录MySQL命令配置

[root@server mysql]# echo $PATH
/root/.local/bin:/root/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin
[root@server mysql]# vim /etc/profile
# 在该文件第二行添加下述内容
export PATH=$PATH:/usr/local/mysql/bin
[root@server mysql]# source /etc/profile
[root@server mysql]# echo $PATH
/root/.local/bin:/root/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/usr
/local/mysql/bin

配置完成后便可通过命令登录MySQL服务器

[root@server ~]# mysql -uroot -p
Enter password:

在创建用户的时候,会自动生成一个初始密码,但是初始密码难以记忆,所以通常我们在登录MySQL后会修改用户密码,所使用的命令为

以root为例

alter user 'root'@'localhost' identified by '123456';

基础命令

MySQL通配符

%:匹配任意个任意字符

—:匹配一个任意字符

查看数据库/表–show

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

mysql> show tables;
+-------------------------+
| Tables_in_mydb2_stuinfo |
+-------------------------+
| student1                |
+-------------------------+
1 row in set (0.00 sec)

以为现实中数据库/表的数量非常多,所以可以搭配通配符进行筛选

mysql> show databases like 's%';
+---------------+
| Database (s%) |
+---------------+
| sys           |
+---------------+
1 row in set (0.00 sec)

show 也可以查看数据库其他信息

mysql> select now();   #查看数据库当前时间
mysql> select version();  #查看数据库版本
mysql> select user();  #查看数据库的登录用户

创建数据库/表–create

create database #数据库名称;


create table #表名(表选项);
#实例
mysql> create table student1(id int,name varchar(30), sex char(2), age int unsigned, score float, addr varchar(50));

配合show可以查看创建数据库/表使用的语句

#数据库
mysql> show create database testdb;
#或
mysql> show create database testdb\G
#表
mysql> show create table student1\G

通过反引号可以创建特殊名称的数据库

mysql> create database `database`;

查看当前数据库

mysql> select database();

切换数据库–use

mysql> use #数据库名称;

删除数据库/表–drop

mysql> drop database #数据库名称;
mysql> drop table #表名;

查看表格式–desc

desc #表名
mysql> desc student1;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id    | int          | YES  |     | NULL    |       |
| name  | varchar(30)  | YES  |     | NULL    |       |
| sex   | char(2)      | YES  |     | NULL    |       |
| age   | int unsigned | YES  |     | NULL    |       |
| score | float        | YES  |     | NULL    |       |
| addr  | varchar(50)  | YES  |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
6 rows in set (0.00 sec)

查看表内容

select * from 表名

写入内容

insert into 表名  value(每一列内容);

insert into 表名(指定列)  value(指定列内容);

修改表名

alter table #旧表名 rename #新表名
或
rename table #旧表名 to #新表名
mysql> alter table student2 rename student3;

mysql> rename table student3 to student4;

新增列

alter table #表名 add #新列名 #选项 #目标列名
mysql> alter table student1 add passwrod char(8);  #默认从后面添加

mysql> alter table student1 add notes varchar(30) after age;  #指定列前

mysql> alter table student1 add aa int first;  #新增第一列

删除列

alter table 表名 drop 列名;

修改列名

alter table 表名 change 旧列名 新列名 列类型;

修改列类型

alter table 表名 modify 列名 新列类型;

修改列位置

alter table 表名 modify 列名 列类型 after 某列;

alter table 表名 modify 列名 列类型 first;

与新增列类似

复制表

复制表结构

create table 新表名 like 源表名

复制表内容

insert into 表名 select * from 源表名;

复制表内容加结构

create table 新表名 select * from 源表名;

语法约束

约束分为表级约束和列级约束:

列级约束:在列信息的后面写入

create table 表名(列名 类型 约束);

#修改
alter table 表名 modify 列名 类型 约束(!!!若不添加约束即为删除)

表级约束:所有列信息后添加

create table 表名(列信息, constraint 约束 约束类型(要约束的列名))
#添加
alter table 表名 add [constraint 约束名] 约束类型(要约束的列名)
 #删除
alter table 表名 drop 约束类型 约束名

不能直接修改表级约束,需删除后在添加

非空约束

列级约束,输入不能为空

not null

null或不写即为删除该约束

默认值约束

列级约束,当输入为空时,默认写入的值

default '默认的值'

列描述–comment

列级约束,没有实际意义,单纯描述列信息

comment '信息'

主键约束

但设置主键约束,那么该列的数据便具有唯一性,切不能为空。

一张表只能有一个主键

但可以添加复合主键,同时约束多列

一般主键为列级约束,符合主键为表级约束

primary key

主键自增长

给主键添加自增长的数值;系统会从已经有的最大值+1,得到一个新的不同的值。

自增长必须是整数,如果不设置初始值,默认从1开始递增

约束的字段必须具备NOT NULL属性

设置自增长的命名

auto_increment

指定自增长的起始值:如果第一个记录设置了字段的初始值那么新增的自增长会从他那个初始值+1,例如第一条记录的序号为100,那么再插入记录会从100往上加

唯一性约束

因为一张表中有很多字段需要唯一性,但是一张表中只能有一个主键,唯一键可以解决表中有多个字段需要唯一性约束的问题

作用:限制某个字段/某列的值不能重复

唯一键和主键的关系:

主键只能有一个,唯一键可以有多个

主键和唯一键不是对立关系而是补充关系,一张表中可以有一个主键,也可以同时具有多个唯一键

示例

create table t4( id int primary key, name varchar(20) unique comment '名子
不能重名,可以为空' );

如果插入数据的过程中两个人的名字一致会提示插入失败,这个是唯一键的作用

注意:就算唯一键冲突,他的自增长字段值不连续。

例如A,B,C,D,B,C重名,依次填入A为1,B为2,C填不进去后去改了个名字又能填入了但是C为4,D为5

外键约束

外键约束也是为了表的完整性存在

概念

主表(父表):被引用的表、被参考的表

从表(子表):引用别人的表,参考别人的表

外键:从表中的某个字段引用自主表的某个字段或多个字段

引用键:主表被引用的字段

外键约束主要定义在从表上,主表则必须是有主键约束或唯一键约束.当定义外键后要求外键列数据必须在主表的主键列存在或为null.

代码关联:主在后从在前

foreign key (从表的字段名称) references 主表名字(主表的字段名称)

注意:

  1. 规则:外键值要么在主表主键存在,要么为NULL;主表主键不能空
  2. 要求:主表先建好、被引用字段是主键/候选键;外键和主表主键数量、类型一致;支持自参照(自己引用自己)
  3. 作用:插入从表数据时自动校验,维护表关联完整性

检查约束

检查约束(check):校验字段值,限制取值范围,过滤无效数据。

非空、默认约束属于特殊check。

MySQL8.0.16前仅语法不生效,8.0.16后强制生效。

设置检查约束的代码

check(salary>0 and salary<10000)

限制的取值范围为0~10000

check_id check(id>0)

检查id一定要大于0的字段

删除表的约束

删除not null约束、default约束
alter table 表名 modify 列名 类型; 
删除unique约束
alter table 表名 drop index 惟一约束名; 
删除primary key约束
alter table 表名 drop primary key; 
删除foreign key约束
alter table 表名 drop foreign key 外键名; 
删除check约束
alter table 表明 drop check 约束名;
深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值