SQL概述

结构化查询语言(Structured Query Language)简称SQL,是一种特殊目的的编程语言,是一种数据库查询和程序设计语言,用于存取数据以及查询、更新和管理关系数据库系统;同时也是数据库脚本文件的扩展名。

dba是数据库管理员database administrator
dbd是数据库开发人员database developer

SQL 是1986年10 月由美国国家标准局(ANSI)通过的数据库语言美国标准,接着,国际标准化组织(ISO)颁布了SQL正式国际标准。1989年4月,ISO提出了具有完整性特征的SQL89标准,1992年11月又公布了SQL92标准,在此标准中,把数据库分为三个级别:基本集、标准集和完全集。

SQL语句结构

结构化查询语言包含6个部分:
一:数据查询语言(DQL:Data Query Language):
其语句,也称为“数据检索语句”,用以从表中获得数据,确定数据怎样在应用程序给出。保留字SELECT是DQL(也是所有SQL)用得最多的动词,其他DQL常用的保留字有WHERE,ORDER BY,GROUP BY和HAVING。这些DQL保留字常与其他类型的SQL语句一起使用。
二:数据操作语言(DML:Data Manipulation Language):
其语句包括动词INSERT,UPDATE和DELETE。它们分别用于添加,修改和删除表中的行。也称为动作查询语言。
三:事务处理语言(TPL):跟shell有点类似 由多条sql语句组成的整体
它的语句能确保被DML语句影响的表的所有行及时得以更新。TPL语句包括BEGIN TRANSACTION,COMMIT和ROLLBACK。
四:数据控制语言(DCL):
它的语句通过GRANT或REVOKE获得许可,确定单个用户和用户组对数据库对象的访问。某些RDBMS可用GRANT或REVOKE控制对表单个列的访问。
五:数据定义语言(DDL):
其语句包括动词CREATE和DROP。在数据库中创建新表或删除表(CREAT TABLE 或 DROP TABLE);为表加入索引等。DDL包括许多与人数据库目录中获得数据有关的保留字。它也是动作查询的一部分。
六:指针控制语言(CCL):
它的语句,像DECLARE CURSOR,FETCH INTO和UPDATE WHERE CURRENT用于对一个或多个表单独行的操作。([dɪˈkler] [ˈkɜ:rsə®]声明游标)[fɛtʃ] into获取到

MySQL语句

关于数据库的操作

查看数据库:

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

注:
1:information_schema这数据库保存了MySQL服务器所有数据库的信息。如数据库名,数据库的表,表栏的数据类型不访问权限等。 [ˈskimə]
2:performance_schema 这是MySQL5.5新增的一个性能优化的引擎:命名PERFORMANCE_SCHEMA [pəˈfɔ:məns]
主要用于收集数据库服务器性能参数。MySQL用户是不能创建存储引擎为PERFORMANCE_SCHEMA的表
3:mysql库是系统库,里面保存有账户信息,权限信息等。
4:mysql5.7增加了sys 系统数据库,通过这个库可以快速的了解系统的元数据信息
元数据是关于数据信息的数据,如数据库名或表名,列的数据类型,或访问权限等。

mysql> use mysql;           #进到mysql库
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -ADatabase changed
mysql> show tables;         #查看表
+---------------------------+
| Tables_in_mysql           |
+---------------------------+
| columns_priv              |
| db                        |
| engine_cost               |
| event                     |
| func                      |
| general_log               |
| gtid_executed             |
| help_category             |
| help_keyword              |
| help_relation             |
| help_topic                |
| innodb_index_stats        |
| innodb_table_stats        |
| ndb_binlog_index          |
| plugin                    |
| proc                      |
| procs_priv                |
| proxies_priv              |
| server_cost               |
| servers                   |
| slave_master_info         |
| slave_relay_log_info      |
| slave_worker_info         |
| slow_log                  |
| tables_priv               |
| time_zone                 |
| time_zone_leap_second     |
| time_zone_name            |
| time_zone_transition      |
| time_zone_transition_type |
| user                      |
+---------------------------+
31 rows in set (0.00 sec)
mysql> show databases \G     #以行的方式显示
*************************** 1. row ***************************
Database: information_schema
*************************** 2. row ***************************
Database: mysql
*************************** 3. row ***************************
Database: performance_schema
*************************** 4. row ***************************
Database: sys
4 rows in set (0.00 sec)
[root@localhost ~]# mysql -e 'show databases' -uroot -p123456  #这种方式用在shell脚本
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
[root@localhost ~]# mysqlshow -uroot -p123456
mysqlshow: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
|     Databases      |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+

创建数据库

语法:create database 数据库名;

创建数据库注意事项:
1)在文件系统中,MySQL的数据存储区将以目录方式表示MySQL数据库。因此,上面命令中的数据库名字必须与操作系统的约束的目录名字一致。例如不允许文件和目录名中有,/,:,*,?,”,<,>,|这些符号,在MySQL数据库名字中这些字母会被自动删除。<遵从目录的约束>
2)数据库的名字不能超过64个字符,包含特殊字符的名字或者是全部由数字或保留字组成的名字必须用单引号``包起来。
3)数据库不能重名。

创建一个test库

mysql> create database test;
Query OK, 1 row affected (0.00 sec)mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| test               |
+--------------------+
5 rows in set (0.00 sec)

数据库存放目录

[root@localhost ~]# ls /var/lib/mysql/
auto.cnf    client-cert.pem  ibdata1      ibtmp1      mysql.sock.lock     public_key.pem   sys
ca-key.pem  client-key.pem   ib_logfile0  mysql       performance_schema  server-cert.pem  test
ca.pem      ib_buffer_pool   ib_logfile1  mysql.sock  private_key.pem     server-key.pem   test1


查看后台执行的详情

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

创建一个有特殊字符的数据库

mysql> create database `HA-test`;
Query OK, 1 row affected (0.00 sec)mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| HA-test            |
| mysql              |
| performance_schema |
| sys                |
| test               |
| test1              |
+--------------------+
7 rows in set (0.00 sec)
[root@localhost mysql]# ll
总用量 122952
-rw-r-----. 1 mysql mysql       56 10月 21 07:25 auto.cnf
-rw-------. 1 mysql mysql     1680 10月 21 07:25 ca-key.pem
-rw-r--r--. 1 mysql mysql     1112 10月 21 07:25 ca.pem
-rw-r--r--. 1 mysql mysql     1112 10月 21 07:25 client-cert.pem
-rw-------. 1 mysql mysql     1676 10月 21 07:25 client-key.pem
drwxr-x---. 2 mysql mysql       20 10月 21 12:26 HA@002dtest     #HA-test
-rw-r-----. 1 mysql mysql      351 10月 21 07:36 ib_buffer_pool
-rw-r-----. 1 mysql mysql 12582912 10月 21 07:36 ibdata1
-rw-r-----. 1 mysql mysql 50331648 10月 21 07:36 ib_logfile0
-rw-r-----. 1 mysql mysql 50331648 10月 21 07:25 ib_logfile1
-rw-r-----. 1 mysql mysql 12582912 10月 21 07:36 ibtmp1

查询当前所在的库,相当于linux的pwd

mysql> use test;
Database changed
mysql> select database();
+------------+
| database() |
+------------+
| test       |
+------------+
1 row in set (0.00 sec)

以这种方式登录可以直接对指定的数据操作

[root@localhost test]# mysql -uroot -p123456 test
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 14
Server version: 5.7.28 MySQL Community Server (GPL)Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.mysql> select database();
+------------+
| database() |
+------------+
| test       |
+------------+
1 row in set (0.00 sec)

查询当前时间,用户,库

mysql> select now(),user(),database();
+---------------------+----------------+------------+
| now()               | user()         | database() |
+---------------------+----------------+------------+
| 2019-10-21 12:35:08 | root@localhost | test       |
+---------------------+----------------+------------+
1 row in set (0.00 sec)

删除数据库

mysql> drop database test;
Query OK, 0 rows affected (0.00 sec)

使用IF EXISTS 子句以避免删除不存在的数据库时出现的MySQL错误信息

mysql> create database if not exists TEST;   #查询TEST,如果不存在则创建
Query OK, 1 row affected (0.00 sec)mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| TEST               |
| mysql              |
| performance_schema |
| sys                |
| test1              |
+--------------------+
6 rows in set (0.00 sec)

关于表的操作
创建表:
语法:create table 表名 (字段名 类型, 字段名 类型, 字段名 类型);
查看表相关信息:
查看表:
要进入到数据库再查看

mysql> use TEST;
Database changed
mysql> show tables;
Empty set (0.00 sec)mysql> create table student(id int(20),name char(40),age int);
Query OK, 0 rows affected (0.41 sec)mysql> show tables;
+----------------+
| Tables_in_TEST |
+----------------+
| student        |
+----------------+
1 row in set (0.00 sec)

查看表的结构:

mysql> desc student;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int(20)  | YES  |     | NULL    |       |
| name  | char(40) | YES  |     | NULL    |       |
| age   | int(11)  | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
3 rows in set (0.38 sec)

int 默认长度11

如果是没有在use到某个库下,需要查看表的方法

mysql> desc TEST.student;   # 常用
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int(20)  | YES  |     | NULL    |       |
| name  | char(40) | YES  |     | NULL    |       |
| age   | int(11)  | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
3 rows in set (0.00 sec)
mysql> explain TEST.student;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int(20)  | YES  |     | NULL    |       |
| name  | char(40) | YES  |     | NULL    |       |
| age   | int(11)  | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
3 rows in set (0.00 sec)
mysql>  show columns from TEST.student;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int(20)  | YES  |     | NULL    |       |
| name  | char(40) | YES  |     | NULL    |       |
| age   | int(11)  | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
3 rows in set (0.00 sec)

会一种常用的就行

查看创建表执行了哪些命令:

mysql> show create table student \G
*************************** 1. row ***************************Table: student
Create Table: CREATE TABLE `student` (`id` int(20) DEFAULT NULL,`name` char(40) DEFAULT NULL,`age` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1 row in set (0.03 sec)

指定表的默认存储引擎和字符集

mysql> create table student2(id int(20),name char(40),age int)ENGINE=MyISAM DEFAULT CHARSET=utf8;
Query OK, 0 rows affected (0.10 sec)mysql> show create table student2 \G
*************************** 1. row ***************************Table: student2
Create Table: CREATE TABLE `student2` (`id` int(20) DEFAULT NULL,`name` char(40) DEFAULT NULL,`age` int(11) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8
1 row in set (0.03 sec)

删除表

mysql> drop table student2;
Query OK, 0 rows affected (0.04 sec)

禁止预读表信息

mysql> use performance_schema;  #切换到数据库的时候,所提示的信息
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

不想有提示可以在登录的时候加上-A参数

[root@localhost test]# mysql -uroot -p123456  -A
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 15
Server version: 5.7.28 MySQL Community Server (GPL)Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.mysql> use performance_schema;
Database changed

修改表名称alter
语法:alter table 表名 rename 新表名;
修改表需要use到表所在的库

mysql> alter table student rename students;  #studen表名修改为students
Query OK, 0 rows affected (0.23 sec)
mysql> show tables;
+----------------+
| Tables_in_TEST |
+----------------+
| students       |
+----------------+
1 row in set (0.01 sec)

修改表中的字段类型
语法:alter table 表名 modify 要修改的字段名 要修改的类型;

mysql> desc students;       #修改前
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int(20)  | YES  |     | NULL    |       |
| name  | char(40) | YES  |     | NULL    |       |
| age   | int(11)  | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
3 rows in set (0.04 sec)mysql> alter table students modify id int(10);   #修改字段id长度
Query OK, 0 rows affected (0.11 sec)
Records: 0  Duplicates: 0  Warnings: 0mysql> desc students;    #修改后
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int(10)  | YES  |     | NULL    |       |
| name  | char(40) | YES  |     | NULL    |       |
| age   | int(11)  | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
3 rows in set (0.00 sec)

修改表中的字段类型和字段名称
语法:alter table 表名 change 原字段名 新字段名 新字段类型;
查了一下官方文档,发现mysql还真的不支持同时修改多个字段,
MODIFY [COLUMN] col_name column_definition
[FIRST | AFTER col_name]

mysql> desc students;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int(10)  | YES  |     | NULL    |       |
| name  | char(40) | YES  |     | NULL    |       |
| age   | int(11)  | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
3 rows in set (0.00 sec)mysql> alter table students change name stname char(20);  #修改name字段的长度
Query OK, 0 rows affected (0.57 sec)
Records: 0  Duplicates: 0  Warnings: 0mysql> desc students;
+--------+----------+------+-----+---------+-------+
| Field  | Type     | Null | Key | Default | Extra |
+--------+----------+------+-----+---------+-------+
| id     | int(10)  | YES  |     | NULL    |       |
| stname | char(20) | YES  |     | NULL    |       |
| age    | int(11)  | YES  |     | NULL    |       |
+--------+----------+------+-----+---------+-------+
3 rows in set (0.00 sec)

注:CHANGE 和MODIFY的区别:
CHANGE 对列进行重命名和更改列的类型,需给定旧的列名称和新的列名称、当前的类型。 MODIFY 可以改变列的类型,此时不需要重命名(不需给定新的列名称)

在表中添加字段
语法:alter table 表名 add 字段名 字段类型;

mysql> alter table students add sex enum('M','W');
Query OK, 0 rows affected (0.30 sec)
Records: 0  Duplicates: 0  Warnings: 0mysql> desc students;
+--------+---------------+------+-----+---------+-------+
| Field  | Type          | Null | Key | Default | Extra |
+--------+---------------+------+-----+---------+-------+
| id     | int(10)       | YES  |     | NULL    |       |
| stname | char(20)      | YES  |     | NULL    |       |
| age    | int(11)       | YES  |     | NULL    |       |
| sex    | enum('M','W') | YES  |     | NULL    |       |
+--------+---------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

指定位置添加字段
在第一列添加一个字段

mysql> alter table students add uid int(10) first;
Query OK, 0 rows affected (0.05 sec)
Records: 0  Duplicates: 0  Warnings: 0mysql> desc students;
+--------+---------------+------+-----+---------+-------+
| Field  | Type          | Null | Key | Default | Extra |
+--------+---------------+------+-----+---------+-------+
| uid    | int(10)       | YES  |     | NULL    |       |
| id     | int(10)       | YES  |     | NULL    |       |
| stname | char(20)      | YES  |     | NULL    |       |
| age    | int(11)       | YES  |     | NULL    |       |
| sex    | enum('M','W') | YES  |     | NULL    |       |
+--------+---------------+------+-----+---------+-------+
5 rows in set (0.00 sec)

在age后面添加一个address字段

mysql> alter table students add address char(40) after age;
Query OK, 0 rows affected (0.16 sec)
Records: 0  Duplicates: 0  Warnings: 0mysql> desc students;
+---------+---------------+------+-----+---------+-------+
| Field   | Type          | Null | Key | Default | Extra |
+---------+---------------+------+-----+---------+-------+
| uid     | int(10)       | YES  |     | NULL    |       |
| id      | int(10)       | YES  |     | NULL    |       |
| stname  | char(20)      | YES  |     | NULL    |       |
| age     | int(11)       | YES  |     | NULL    |       |
| address | char(40)      | YES  |     | NULL    |       |
| sex     | enum('M','W') | YES  |     | NULL    |       |
+---------+---------------+------+-----+---------+-------+
6 rows in set (0.00 sec)

删除表中字段
语法:alter table 表名 drop 字段名 ;

mysql> alter table students drop address;
Query OK, 0 rows affected (0.15 sec)
Records: 0  Duplicates: 0  Warnings: 0mysql> desc students;
+--------+---------------+------+-----+---------+-------+
| Field  | Type          | Null | Key | Default | Extra |
+--------+---------------+------+-----+---------+-------+
| uid    | int(10)       | YES  |     | NULL    |       |
| id     | int(10)       | YES  |     | NULL    |       |
| stname | char(20)      | YES  |     | NULL    |       |
| age    | int(11)       | YES  |     | NULL    |       |
| sex    | enum('M','W') | YES  |     | NULL    |       |
+--------+---------------+------+-----+---------+-------+
5 rows in set (0.04 sec)

关于记录的操作
插入字段<记录>insert:
语法:insert into 表名values (字段值1,字段值2, 字段值3);

mysql> insert into students values(44,1,'zhangs',21,'m');
Query OK, 1 row affected (0.06 sec)
mysql> select * from students;
+------+------+--------+------+------+
| uid  | id   | stname | age  | sex  |
+------+------+--------+------+------+
|   44 |    1 | zhangs |   21 | M    |
+------+------+--------+------+------+
1 row in set (0.03 sec)

同时插入多条,使用,分开

mysql> insert into students (id,stname) values(4,'xie');
Query OK, 1 row affected (0.05 sec)

查询表中记录
语法:select * from 表名称;

mysql> select * from students;       #  *代表所有
+------+------+--------+------+------+
| uid  | id   | stname | age  | sex  |
+------+------+--------+------+------+
|   44 |    1 | zhangs |   21 | M    |
| NULL |    4 | xie    | NULL | NULL |
+------+------+--------+------+------+
2 rows in set (0.00 sec)

当字段比较多的时候我们也可以使用\G

mysql> select * from students \G         #查看某个字段,可以指定字段查询
*************************** 1. row ***************************uid: 44id: 1
stname: zhangsage: 21sex: M
*************************** 2. row ***************************uid: NULLid: 4
stname: xieage: NULLsex: NULL
*************************** 3. row ***************************uid: 23id: NULL
stname: xieage: 23sex: NULL
3 rows in set (0.00 sec)
mysql> select stname from students \G
*************************** 1. row ***************************
stname: zhangs
*************************** 2. row ***************************
stname: xie
*************************** 3. row ***************************
stname: xie
3 rows in set (0.00 sec)
mysql> select uid,stname  from students \G
*************************** 1. row ***************************uid: 44
stname: zhangs
*************************** 2. row ***************************uid: NULL
stname: xie
*************************** 3. row ***************************uid: 23
stname: xie
3 rows in set (0.03 sec)
mysql> select uid,stname  from students;
+------+--------+
| uid  | stname |
+------+--------+
|   44 | zhangs |
| NULL | xie    |
|   23 | xie    |
+------+--------+
3 rows in set (0.00 sec)mysql> select  * from  students where uid=44;  # 指定参数查询
+------+------+--------+------+------+
| uid  | id   | stname | age  | sex  |
+------+------+--------+------+------+
|   44 |    1 | zhangs |   21 | M    |
+------+------+--------+------+------+
1 row in set (0.17 sec)

查看别的数据库的表或者不在本数据库上进行查看
语法:SELECT 字段 FROM 数据库名.表名;

mysql> use mysql;
Database changed
mysql> select * from TEST.students;  #跨库查询,查看某个数据库下指定的表内容,数据库名.表名
+------+------+--------+------+------+
| uid  | id   | stname | age  | sex  |
+------+------+--------+------+------+
|   44 |    1 | zhangs |   21 | M    |
| NULL |    4 | xie    | NULL | NULL |
|   23 | NULL | xie    |   23 | NULL |
+------+------+--------+------+------+
3 rows in set (0.00 sec)

查询null值

mysql> select * from TEST.students where age is null;
+------+------+--------+------+------+
| uid  | id   | stname | age  | sex  |
+------+------+--------+------+------+
| NULL |    4 | xie    | NULL | NULL |
+------+------+--------+------+------+
1 row in set (0.30 sec)

查询空值

mysql> select * from TEST.students where age='';
Empty set (0.00 sec)

删除记录

删除id为4的行

mysql> delete from students where id=4;
Query OK, 1 row affected (0.05 sec)mysql> select * from students;
+------+------+--------+------+------+
| uid  | id   | stname | age  | sex  |
+------+------+--------+------+------+
|   23 | NULL | xie    |   23 | NULL |
+------+------+--------+------+------+
1 row in set (0.00 sec)

删除sex为空的行

mysql> delete from students where sex is null;
Query OK, 1 row affected (0.01 sec)mysql> select * from students;
Empty set (0.00 sec)

更新记录

mysql> select * from students;
+------+------+--------+------+------+
| uid  | id   | stname | age  | sex  |
+------+------+--------+------+------+
|   23 | NULL | xie    |   23 | NULL |
|   44 |    1 | zhangs |   21 | M    |
|   45 |    2 | dz     |   21 | W    |
|    5 |    3 | dz     |   21 | W    |
+------+------+--------+------+------+
4 rows in set (0.00 sec)mysql> update students set sex='M' where uid=23;
Query OK, 1 row affected (0.04 sec)
Rows matched: 1  Changed: 1  Warnings: 0mysql> select * from students;
+------+------+--------+------+------+
| uid  | id   | stname | age  | sex  |
+------+------+--------+------+------+
|   23 | NULL | xie    |   23 | M    |
|   44 |    1 | zhangs |   21 | M    |
|   45 |    2 | dz     |   21 | W    |
|    5 |    3 | dz     |   21 | W    |
+------+------+--------+------+------+
4 rows in set (0.00 sec)

所有的id字段都变为1

mysql> update students set id=1;
Query OK, 3 rows affected (0.00 sec)
Rows matched: 4  Changed: 3  Warnings: 0mysql> select * from students;
+------+------+--------+------+------+
| uid  | id   | stname | age  | sex  |
+------+------+--------+------+------+
|   23 |    1 | xie    |   23 | M    |
|   44 |    1 | zhangs |   21 | M    |
|   45 |    1 | dz     |   21 | W    |
|    5 |    1 | dz     |   21 | W    |
+------+------+--------+------+------+
4 rows in set (0.00 sec)

同时更新多个字段时候用,号隔开

SQL基础条件查询语句

语法:select 字段名1,字段名2 from 表名 [where 条件];
查询students表中的name,age

mysql> select stname,age from students;
+--------+------+
| stname | age  |
+--------+------+
| xie    |   23 |
| zhangs |   21 |
| dz     |   21 |
| dz     |   21 |
+--------+------+
4 rows in set (0.00 sec)

去重复查询distinct

mysql> select distinct stname,age from students;
+--------+------+
| stname | age  |
+--------+------+
| xie    |   23 |
| zhangs |   21 |
| dz     |   21 |
+--------+------+
3 rows in set (0.30 sec)

查询age=21的,显示id,stname,age

mysql>  select  distinct id,stname,age from students where age=21;
+------+--------+------+
| id   | stname | age  |
+------+--------+------+
|    1 | zhangs |   21 |
|    1 | dz     |   21 |
+------+--------+------+
2 rows in set (0.00 sec)

mysql的distinct可以对*使用

mysql> select distinct * from students;
+------+------+--------+------+------+
| uid  | id   | stname | age  | sex  |
+------+------+--------+------+------+
|   23 |    1 | xie    |   23 | M    |
|   44 |    1 | zhangs |   21 | M    |
|   45 |    1 | dz     |   21 | W    |
|    5 |    1 | dz     |   21 | W    |
+------+------+--------+------+------+
4 rows in set (0.00 sec)mysql> select * from students;
+------+------+--------+------+------+
| uid  | id   | stname | age  | sex  |
+------+------+--------+------+------+
|   23 |    1 | xie    |   23 | M    |
|   44 |    1 | zhangs |   21 | M    |
|   45 |    1 | dz     |   21 | W    |
|    5 |    1 | dz     |   21 | W    |
+------+------+--------+------+------+
4 rows in set (0.00 sec)

使用and和or进行多条件查询
or和and 同时存在时,先算and的两边值,逻辑与先执行

mysql> select id ,stname,age from students where  id>3 and age>20;
+------+--------+------+
| id   | stname | age  |
+------+--------+------+
|    8 | zhangs |   21 |
|    7 | dd     |   21 |
+------+--------+------+
2 rows in set (0.00 sec)
mysql> select id,stname,age from students where id>4 or age>21;
+------+--------+------+
| id   | stname | age  |
+------+--------+------+
|    3 | xie    |   23 |
|    8 | zhangs |   21 |
|    7 | dd     |   21 |
+------+--------+------+
3 rows in set (0.00 sec)
mysql> select * from students where stname='dd' and (age=21 or age=23);
+------+------+--------+------+------+
| uid  | id   | stname | age  | sex  |
+------+------+--------+------+------+
|   45 |    7 | dd     |   21 | W    |
+------+------+--------+------+------+
1 row in set (0.00 sec)

注意and和or都是用的时候的逻辑关系

MySQL区分大小写查询
Mysql查询默认是不区分大小写的

mysql> select stname from students where stname='dd';
+--------+
| stname |
+--------+
| dd     |
| DD     |
| DD     |
| DD     |
+--------+
4 rows in set (0.00 sec)

解决

mysql> select * from students where binary stname='dd';
+------+------+--------+------+------+
| uid  | id   | stname | age  | sex  |
+------+------+--------+------+------+
|   45 |    7 | dd     |   21 | W    |
+------+------+--------+------+------+
1 row in set (0.04 sec)

BINARY是类型转换运算符,它用来强制它后面的字符串为一个二进制字符串,可以理解为在字符串比较的时候区分大小写。

MySQL查询排序

语法:select distinct 字段1,字段2 from 表名order by 字段名;
默认为升序 asc

mysql> select distinct id from students order by id asc;
+------+
| id   |
+------+
|    1 |
|    3 |
|    6 |
|    7 |
|    8 |
|   11 |
+------+
6 rows in set (0.00 sec)
mysql> select distinct id from students order by id desc;
+------+
| id   |
+------+
|   11 |
|    8 |
|    7 |
|    6 |
|    3 |
|    1 |
+------+
6 rows in set (0.00 sec)

关于MySQL命令帮助

mysql> help show;
Name: 'SHOW'
Description:
SHOW has many forms that provide information about databases, tables,
columns, or status information about the server. This section describes
those following:SHOW {BINARY | MASTER} LOGS
SHOW BINLOG EVENTS [IN 'log_name'] [FROM pos] [LIMIT [offset,] row_count]
SHOW CHARACTER SET [like_or_where]
SHOW COLLATION [like_or_where]
SHOW [FULL] COLUMNS FROM tbl_name [FROM db_name] [like_or_where]
SHOW CREATE DATABASE db_name
SHOW CREATE EVENT event_name
SHOW CREATE FUNCTION func_name
SHOW CREATE PROCEDURE proc_name
SHOW CREATE TABLE tbl_name
SHOW CREATE TRIGGER trigger_name
SHOW CREATE VIEW view_name
SHOW DATABASES [like_or_where]
SHOW ENGINE engine_name {STATUS | MUTEX}
SHOW [STORAGE] ENGINES
SHOW ERRORS [LIMIT [offset,] row_count]
SHOW EVENTS
SHOW FUNCTION CODE func_name
SHOW FUNCTION STATUS [like_or_where]
SHOW GRANTS FOR user
SHOW INDEX FROM tbl_name [FROM db_name]
SHOW MASTER STATUS
SHOW OPEN TABLES [FROM db_name] [like_or_where]
SHOW PLUGINS
SHOW PROCEDURE CODE proc_name
SHOW PROCEDURE STATUS [like_or_where]
SHOW PRIVILEGES
SHOW [FULL] PROCESSLIST
SHOW PROFILE [types] [FOR QUERY n] [OFFSET n] [LIMIT n]
SHOW PROFILES
SHOW RELAYLOG EVENTS [IN 'log_name'] [FROM pos] [LIMIT [offset,] row_count]
SHOW SLAVE HOSTS
SHOW SLAVE STATUS [FOR CHANNEL channel]
SHOW [GLOBAL | SESSION] STATUS [like_or_where]
SHOW TABLE STATUS [FROM db_name] [like_or_where]
SHOW [FULL] TABLES [FROM db_name] [like_or_where]
SHOW TRIGGERS [FROM db_name] [like_or_where]
SHOW [GLOBAL | SESSION] VARIABLES [like_or_where]
SHOW WARNINGS [LIMIT [offset,] row_count]like_or_where:LIKE 'pattern'| WHERE exprIf the syntax for a given SHOW statement includes a LIKE 'pattern'
part, 'pattern' is a string that can contain the SQL % and _ wildcard
characters. The pattern is useful for restricting statement output to
matching values.Several SHOW statements also accept a WHERE clause that provides more
flexibility in specifying which rows to display. See
https://dev.mysql.com/doc/refman/5.7/en/extended-show.html.URL: https://dev.mysql.com/doc/refman/5.7/en/show.html
mysql> help select;
Name: 'SELECT'
Description:
Syntax:    #语法
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]]SELECT is used to retrieve rows selected from one or more tables, and
can include UNION statements and subqueries. See [HELP UNION], and
https://dev.mysql.com/doc/refman/5.7/en/subqueries.html.The most commonly used clauses of SELECT statements are these:o Each select_expr indicates a column that you want to retrieve. Theremust be at least one select_expr.o table_references indicates the table or tables from which to retrieverows. Its syntax is described in [HELP JOIN].o SELECT supports explicit partition selection using the PARTITION witha list of partitions or subpartitions (or both) following the name ofthe table in a table_reference (see [HELP JOIN]). In this case, rowsare selected only from the partitions listed, and any otherpartitions of the table are ignored. For more information andexamples, seehttps://dev.mysql.com/doc/refman/5.7/en/partitioning-selection.html.SELECT ... PARTITION from tables using storage engines such as MyISAMthat perform table-level locks (and thus partition locks) lock onlythe partitions or subpartitions named by the PARTITION option.For more information, seehttps://dev.mysql.com/doc/refman/5.7/en/partitioning-limitations-locking.html.o The WHERE clause, if given, indicates the condition or conditionsthat rows must satisfy to be selected. where_condition is anexpression that evaluates to true for each row to be selected. Thestatement selects all rows if there is no WHERE clause.In the WHERE expression, you can use any of the functions andoperators that MySQL supports, except for aggregate (summary)functions. Seehttps://dev.mysql.com/doc/refman/5.7/en/expressions.html, andhttps://dev.mysql.com/doc/refman/5.7/en/functions.html.SELECT can also be used to retrieve rows computed without reference to
any table.URL: https://dev.mysql.com/doc/refman/5.7/en/select.html

Yum 安装mysql5.7的方法:

CentOS 7版本下载

[root@localhost ~]# rpm -Uvh https://repo.mysql.com//yum/mysql-5.7-community/el/7/x86_64/mysql57-community-release-el7-10.noarch.rpm
[root@localhost ~]#yum list
[root@localhost ~]#yum -y install mysql-community-server

第一次通过# grep “password” /var/log/mysqld.log 命令获取MySQL的临时密码
用该密码登录到服务端后,必须马上修改密码,不然操作查询时报错误
刚开始设置的密码必须符合长度,且必须含有数字,小写或大写字母,特殊字符。
如果想设置简单密码,如下操作:
方法一:首先,修改validate_password_policy参数的值

mysql> set global validate_password_policy=0;  #定义复杂度
mysql> set global validate_password_length=1;  #定义长度 默认是8
mysql>set password for 'root'@'localhost'=password('123456');
mysql> flush privileges;

方法二:在/etc/my.cnf 可关闭密码强度审计插件,重启mysql服务
validate-password=ON/OFF/FORCE/FORCE_PLUS_PERMANENT: 决定是否使用该插件(及强制/永久强制使用)。

查询 当前数据库用户和主机

select Host, User, from user;
+---------------+---------------+
| Host          | User          |
+---------------+---------------+
| 192.168.195.% | confluence    |
| localhost     | mysql.session |
| localhost     | mysql.sys     |
| localhost     | root          |
+---------------+---------------+
4 rows in set (0.00 sec)

Mysql基础-常用sql语句相关推荐

  1. MYSQL基础之SQL语句概念,规范,以及了解SELECT

    SQL 的简介 1974年,IBM研究员发布了一篇揭开了数据库技术的论文<SEQUEL:一门机构化的英语查询语言>,直到新增这个查询语言也没有太大的变化.可以看出SQL语言的生命力之强. ...

  2. MYSQL基础(sql语句)

    SQL语句 文章目录 SQL语句 SQL语句的多种类型: 1.DDL操作 1.1 数据库DDL操作 1.2 表DDL操作 1.3 用户DDL操作 1.4 查看命令SHOW 1.5 ALTER修改操作 ...

  3. SQL基础:常用SQL语句详解(转)

    到今天为止,人们对关系数据库做了大量的研究,并开发出关系数据语言,为操作关系数据库提供了方便的用户接口.关系数据语言目前有几十种,具有增加.删除.修改.查询.数据定义与控制等完整的数据库操作功能.通常 ...

  4. php mysql数据库常用sql语句命令集合

    /*  ****** author:Vericlongmore ******  ****** update date:2012-04-05 *****  ****** spot:beijing *** ...

  5. MySQL基础----动态SQL语句

    动态sql语句基本语法  1 :普通SQL语句可以用Exec执行 eg:   Select * from tableName           Exec('select * from tableNa ...

  6. MySQL生产常用SQL语句汇总

    #配置参数查询部分 #1.查询MySQL data目录 show variables like 'datadir';#空间统计部分 #1.查看数据库各个表的空间占用情况,版本1 select tabl ...

  7. MYSQL数据库初窥门径, SQL语句地熟练使用, 图形化界面提高效率

    目录 一. 前文简介 二. MYSQL简介 2.1 什么是数据库 2.2数据库地特点以及作用 三.MYSQL基础操作(SQL语句) 3.1连接数据库 3.2数据库的语法特点,以及数据库必会操作 数据操 ...

  8. mysql sql诊断建议_MySQL诊断调优常用SQL语句

    帮忙多点点文章末右下角的"好看"支持下,也可以将本文分享到朋友圈或你身边的朋友,谢谢 在很多时候,我们需要通过SQL语句来查看MySQL执行SQL的情况,例如查看SQL执行队列,是 ...

  9. 经典MySQL语句大全和常用SQL语句命令的作用。

    转载自 http://blog.csdn.net/suyu_yuan/article/details/51784893 转自网络: 经典MSSQL语句大全和常用SQL语句命令的作用  下列语句部分是M ...

  10. 常用SQL语句 - 基于MySQL数据库

    常用SQL语句 - 基于MySQL数据库 基础 连接数据库 mysql -h10.20.66.32 -uroot -p123456 -h后面是mysqlServer所在地址,-u后面是用户名,-p后面 ...

最新文章

  1. 解决Could not open requirements file: [Errno 2] No such file or directory: ‘requirements.txt‘问题
  2. kafka消费者如何读同一生产者消息_Kafka消费者生产者实例
  3. 广播,实现强制下线功能(项目文件已上传GitHub)
  4. SAP CRM One Order函数CRM_Object_FILL_OW的设计原理
  5. 搞技术多少要有点危机意识,切不可温水煮青蛙
  6. java获得电脑性能_Java:使用SingletonStream获得性能
  7. 台式机没有显示计算机图标,为什么台式电脑没有喇叭图标
  8. CCNA 学习笔记(四)--路由协议(RIP)
  9. java课程之团队开发冲刺阶段1.7
  10. AI表情迁移、电影字幕自动翻译等,原来是这么玩的!
  11. 信用卡号校验java_ES reduce 一行代码解决信用卡号验证问题
  12. 课时4:改进我们的小游戏
  13. wps mysql ubuntu_Ubuntu 安装WPS
  14. 轻松解决ArcGIS Pro 安装中文汉化包或离线帮助文档时报错“指定路径为空”
  15. 5G关键技术之D2D通信技术
  16. html 投票系统,投票系统 html页面
  17. matlab图像去散焦,matlab为图像加运动模糊和散焦模糊
  18. 微信小程序下载文件wx.saveFile
  19. JAVA PDF 转 PNG
  20. python画一个爱心

热门文章

  1. c语言装b程序,C语言打造表白和装逼利器:亲爱的让我们相爱在一起,酷炫的梦幻...
  2. Python黑客帝国装逼代码
  3. 邮箱服务器如何配置?POP和IMAP如何定义?
  4. Mybatis事务管理机制<transactionManager>
  5. webpack中swipe的安装和使用
  6. 心理学第二周学习笔记:心理学的历史和流派
  7. 线性判别分析 LDA总结
  8. 如何让图片按照1 2 3排列不带括号
  9. ANSYS workench 物体受力分析
  10. 浏览器transform介绍