MySQL database, from entry to proficiency: the third part - MySQL database specification and basic query statement


directory hierarchy

MySQL database, from entry to proficiency: Part 1 - Detailed explanation of MySQL concepts
MySQL database, from entry to proficiency: Part 2 - Comparison of MySQL relational database and non-relational database
MySQL database, from entry to proficiency: Part 3 Part - MySQL database specifications and basic query statements
MySQL database, from entry to proficiency: part four - commonly used operators in MySQL and their usage
MySQL database, from entry to proficiency: part five - MySQL sorting and
pagingMySQL Database, from entry to proficiency: Part 6—Comprehensively master MySQL multi-table query skills
MySQL database, from entry to proficiency:
Part 7—Application of MySQL single-row functions Aggregate Function Practical Exploration: Optimizing the SELECT Process to Help Efficiently Query
the MySQL Database, from Beginner to Master: Part 9 - MySQL Subquery
MySQL Database, from Beginner to Master: Part 10 - MySQL Table Creation and Management Guide
MySQL Database, from From entry to proficiency: Part 11 - Addition, deletion and modification guide for MySQL data processing
MySQL database, from entry to proficiency: Part 12 - Detailed explanation of MySQL data types
MySQL database, from entry to proficiency: Part 13 - MySQL Detailed Explanation of Data Table Constraints on
MySQL Database, From Beginner to Master: Part Fourteen——MySQL View Detailed Explanation of
MySQL Database, From Beginner to Master: Part Fifteen——Detailed Explanation of MySQL Stored Procedures and Functions on
MySQL Database, From Beginner to Master: Part 1 Sixteen articles——MySQL variables, process control and cursors explain
MySQL database in detail, from entry to mastery: Article seventeen——How to use MySQL triggers and precautions
MySQL database, from entry to proficiency: Part 18 - Full Analysis of New Features of MySQL 8

THIS IS END!


Preface
MySQL is a popular relational database management system widely used in various industries. This article is dedicated to introducing MySQL database specifications and basic SELECT statements to help readers understand how to better use and manage MySQL databases.

Abstract
This article is mainly divided into two aspects. The first part introduces the MySQL database specification and its background knowledge, including database naming specification, field naming specification, data type, index and key, etc., hoping to help readers follow the MySQL database specification and improve database performance. quality.

The second part introduces the basic SELECT statement, which is used to select data from the database. Demonstrate the basic usage and grammatical rules of the SELECT statement through examples to help readers better understand and apply the SELECT statement.


Part 3_MySQL database specification and basic query statement

1. SQL overview

1.1 SQL background knowledge

In 1946, the world's first computer was born. Today, the Internet developed by this computer has become a world of its own. In the past few decades, countless technologies and industries have been ups and downs in this river and lake, some are just in the ascendant, and some have experienced several scenes of ups and downs. But in this vast fluctuation, there is a technology that has never disappeared, even "old and strong", and that is SQL.

45 years ago, that is, in 1974, IBM researchers published a paper "SEQUEL: A Structured English Query Language" that unveiled database technology. Until today, this structured query language has not changed much. Compared with other languages, the half-life of SQL can be said to be very long.

Whether it is a front-end engineer or a back-end algorithm engineer, they will definitely deal with data, and they all need to know how to quickly and accurately extract the data they want. Not to mention data analysts, whose job is to work with data and organize different reports to guide business decisions.

SQL (Structured Query Language, Structured Query Language) is a database application language that uses a relational model and directly deals with data. It was developed by IBM in the 1970s. Later, the American National Standards Institute (ANSI) began to formulate SQL standards, including SQL-86, SQL-89, SQL-92, SQL-99 and other standards.

SQL has two important standards, namely SQL92 and SQL99, which respectively represent the SQL standards promulgated in 1992 and 1999, and the SQL language we use today still follows these standards.

Different database manufacturers support SQL statements, but all have unique content

Provide a well-known website for learning, if you are interested, you can take a look (free double-click to open
insert image description here

1.2 SQL Language Ranking List

Since SQL joined the TIOBE programming language list, it has remained in the Top 10.
insert image description here

1.3 SQL classification

The SQL language is mainly divided into the following three categories in terms of functions:

  1. DDL (Data Definition Languages, Data Definition Language), these statements define different database objects such as databases, tables, views, indexes, etc., and can also be used to create, delete, and modify the structure of databases and data tables.

    The main statement keywords include CREATE (create structure), DROP (delete structure), ALTER (modify structure), RENAME (rename), TRUNCATE (empty), etc.

  2. DML (Data Manipulation Language, Data Manipulation Language), used to add, delete, update and query database records, and check data integrity.

    2.1 The main statement keywords include INSERT, DELETE, UPDATE, SELECT, etc. (data in the database for operation database addition, deletion, modification and query).

    2.2 SELECT is the foundation of the SQL language and is the most important.

  3. DCL (Data Control Language, Data Control Language), used to define databases, tables, fields, user access rights and security levels.

    The main statement keywords include GRANT (granting authority), REVOKE (recycling authority), COMMIT (committing, confirming the modified data), ROLLBACK (rolling back the transaction), SAVEPOINT (rolling back the specific save point), etc.

Because query statements are used very frequently, many people single out query statements as one category: DQL (Data Query Language). There is also a separate COMMIT and ROLLBACK called TCL (Transaction Control Language, transaction control language).

2. Rules and specifications of SQL language

  • QL can be written on one or more lines. For readability, write clauses on separate lines, using indentation where necessary
  • Each command ends with ; or \g or \G (in special cases, such as in liunx)
  • Keywords cannot be abbreviated and cannot be broken into lines
  • About punctuation
  1. It must be ensured that all (), single quotes, and double quotes end in pairs

  2. The half-width input method in English must be used

  3. Data of string type and date time type can be represented by single quotes (' ')

  4. The alias of the column, try to use double quotes (" "), and it is not recommended to omit as

2.2 SQL capitalization specification (recommended compliance)

  • MySQL is case insensitive on Windows

  • MySQL is case sensitive in Linux environment

     	数据库名、表名、表的别名、变量名是严格区分大小写的
     	关键字、函数名、列名(或字段名)、列的别名(字段的别名) 是忽略大小写的。
    
  • It is recommended to adopt a unified writing standard:

     数据库名、表名、表别名、字段名、字段别名等都小写
     SQL 关键字、函数名、绑定变量等都大写
    

2.3 Notes

A comment structure of the following format can be used:

Single-line comment: #Comment text (MySQL-specific way)
single-line comment: -- comment text (– must contain a space after it.)
Multi-line comment: /* comment text*

2.4 Naming rules (for now)

  • Database and table names must not exceed 30 characters, and variable names are limited to 29 characters
  • Must only contain A–Z, a–z, 0–9, _ a total of 63 characters
  • Object names such as database names, table names, and field names should not contain spaces
  • In the same MySQL software, databases cannot have the same name; in the same library, tables cannot have the same name; in the same table, fields cannot have the same name
  • You must ensure that your fields do not conflict with reserved words, database systems, or common methods. If you insist, enclose the SQL statement with ` (emphasis)
  • Keep the field names and types consistent. Be sure to ensure consistency when naming fields and specifying data types for them. If the data type is an integer in one table, don't change it to a character in another table

Example:

#以下两句是一样的,不区分大小写
show databases;
SHOW DATABASES;

#创建表格
#create table student info(...); #表名错误,因为表名有空格
create table student_info(...);
#其中order使用``飘号,因为order和系统关键字或系统函数名等预定义标识符重名了

CREATE TABLE `order`(
id INT,
lname VARCHAR(20)
);

select id as "编号", `name` as "姓名" from t_stu; #起别名时,as都可以省略
select id as 编号, `name` as 姓名 from t_stu; #如果字段别名中没有空格,那么可以省略""
select id as 编 号, `name` as 姓 名 from t_stu; #错误,如果字段别名中有空格,那么不能省略""

2.5 Data Import Instructions

Log in to mysql on the command line client and use the source command to import

mysql -u root -p  回车自己输入自己的密码
use depteruser   指定数据的库

import sql file

mysql> source d:\mysqldb.sql

view sql file

mysql> desc employees;
+----------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------------+-------------+------+-----+---------+-------+
| employee_id | int(6) | NO | PRI | 0 | |
| first_name | varchar(20) | YES | | NULL | |
| last_name | varchar(25) | NO | | NULL | |
| email | varchar(25) | NO | UNI | NULL | |
| phone_number | varchar(20) | YES | | NULL | |
| hire_date | date | NO | | NULL | |
| job_id | varchar(10) | NO | MUL | NULL | |
| salary | double(8,2) | YES | | NULL | |
| commission_pct | double(2,2) | YES | | NULL | |
| manager_id | int(6) | YES | MUL | NULL | |
| department_id | int(4) | YES | MUL | NULL | |
+----------------+-------------+------+-----+---------+-------+
11 rows in set (0.00 sec)

Another one below
insert image description here

3. Basic SELECT statement

3.0 SELECT…

SELECT 1; #没有任何子句
SELECT 9/2; #没有任何子句

He can perform simple calculations

SELECT 1+5 ,9*2  FROM DUAL; #dual 伪表 结构
SELECT 1+5 ,9*2
```!



## 3.1 SELECT ... FROM

**语法**:

```sql
SELECT 标识选择哪些列
FROM 标识从哪个表中选择

Select all columns:

SELECT *
FROM departments;

insert image description here

In general, unless you need to use all the field data in the table, it is best not to use the wildcard '*'. Using wildcards saves time entering query statements, but fetching data for columns you don't need often slows down the query and the applications you use. The advantage of wildcards is that they can be used to get the names of the columns you want when you don't know them.
In a production environment, it is not recommended that you directly use SELECT * to query.

Select specific columns:

SELECT department_id, location_id
FROM departments;

insert image description here
insert image description here

SQL statements in MySQL are case-insensitive, so SELECT and select have the same function. However, many developers are used to uppercase keywords and lowercase data columns and table names. Readers should also develop a good programming habit , the code written in this way is easier to read and maintain.

3.2 Column aliases

  • rename a column
  • easy to calculate
  • Immediately following the column name, you can also add the keyword AS between the column name and the alias. The alias uses double quotes so that the alias contains spaces or special characters and is case-sensitive.
  • AS can be omitted
  • It is recommended that the alias be short and familiar

example

SELECT last_name AS name, commission_pct comm
FROM employees;

insert image description here

SELECT last_name "Name", salary*12 "Annual Salary"
FROM employees;

insert image description here

#别名
#第一种方式  相当于给查出来的数据换个名字
#原数据
SELECT employee_id,last_name,department_id FROM employees;

SELECT employee_id empid,last_name lastna,department_id deptid FROM employees;
#第二种 用as 可以忽略 第一种已经说明了
SELECT employee_id AS empid,last_name AS lastna,department_id AS deptid FROM employees;
#第三种 也可用中文
SELECT employee_id AS "部门ID",last_name  "姓",department_id  "部门编号" FROM employees;

insert image description here
insert image description here
insert image description here

insert image description here

SELECT employee_id AS "部门ID",last_name  "姓",department_id  "部门编号" ,salary*10 "lee" FROM employees;

insert image description here

3.3 Remove duplicate rows

By default, the query returns all rows, including duplicates.

SELECT department_id
FROM employees;

insert image description here
Use the keyword DISTINCT in the SELECT statement to remove duplicate rows

SELECT DISTINCT department_id
FROM employees;

insert image description here
Targeted at:

SELECT DISTINCT department_id,salary
FROM employees;

There are two points to note here:

  1. DISTINCT needs to be placed in front of all column names. If it is written as SELECT salary, DISTINCT department_idFROM employees will report an error.
  2. DISTINCT actually deduplicates the combination of all the following column names. You can see that the final result is 74 items, because the 74 department IDs are different, and they all have the attribute value of salary. If you want to see what are the different departments (department_id), you only need to write DISTINCT department_id, and you don’t need to add other column names later

3.4 Null values ​​participate in operations

All operators or column values ​​encounter a null value, and the result of the operation is null

1. Null value: null
2.null is not equal to 0, '', 'NULL'

SELECT employee_id,salary,commission_pct,
12 * salary * (1 + commission_pct) "annual_sal"
FROM employees;

Here you must pay attention, in MySQL, a null value is not equal to an empty string. An empty string has length 0, and a null value has length NULL. Moreover, in MySQL, null values ​​take up space.

3.5 Emphasis

Incorrect

mysql> SELECT * FROM ORDER;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'ORDER' at
line 1

correct

mysql> SELECT * FROM `ORDER`;
+----------+------------+
| order_id | order_name |
+----------+------------+
| 1 | shkstart |
| 2 | tomcat |
| 3 | dubbo |
+----------+------------+
3 rows in set (0.00 sec)
mysql> SELECT * FROM `order`;
+----------+------------+
| order_id | order_name |
+----------+------------+
| 1 | shkstart |
| 2 | tomcat |
| 3 | dubbo |
+----------+------------+
3 rows in set (0.00 sec)

Conclusion
We need to ensure that the fields and table names in the table do not conflict with reserved words, database systems or common methods. If they are really the same, please use a pair of `` (emphasis marks) in the SQL statement.

ORDER is a keyword plus '', it will be regarded as a table;

eg:  ORDER 替换为 `ORDER`

3.6 5. Query constants

SELECT queries can also query constants. Yes, it is to add a fixed constant column to the SELECT query result. The value of this column is specified by us, rather than dynamically fetched from the data table.

You might ask why do we even need to query constants?

The SELECT syntax in SQL does provide this function. Generally speaking, we only query data from one table, and usually do not need to add a fixed constant column, but if we want to integrate different data sources, use the constant column as the table's mark, you need to query the constant.

For example, we want to query the names of employees in the employees data table, and add a field corporation at the same time. The fixed value of this field is "Silicon Valley", which can be written as follows:

SELECT '小超' as corporation, last_name FROM employees;

# 默语  文超 都是常数  小超也是只不过他加了as 别名 相当于给我 小超的表换成名字  corporation
SELECT  '默语' ,'文超','小超' as corporation, last_name FROM employees;

insert image description here

4. Show table structure

Use the DESCRIBE or DESC command to indicate the table structure.

DESCRIBE employees;DESC employees;
mysql> desc employees;
+----------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------------+-------------+------+-----+---------+-------+
| employee_id | int(6) | NO | PRI | 0 | |
| first_name | varchar(20) | YES | | NULL | |
| last_name | varchar(25) | NO | | NULL | |
| email | varchar(25) | NO | UNI | NULL | |
| phone_number | varchar(20) | YES | | NULL | |
| hire_date | date | NO | | NULL | |
| job_id | varchar(10) | NO | MUL | NULL | |
| salary | double(8,2) | YES | | NULL | |
| commission_pct | double(2,2) | YES | | NULL | |
| manager_id | int(6) | YES | MUL | NULL | |
| department_id | int(4) | YES | MUL | NULL | |
+----------------+-------------+------+-----+---------+-------+
11 rows in set (0.00 sec)

insert image description here

Among them, the meaning of each field is explained as follows:

Field : Indicates the field name.
Type : Indicates the field type, where barcode and goodsname are of text type, and price is of integer type.
Null : Indicates whether the column can store NULL values.
Key : Indicates whether the column is indexed. PRI indicates that the column is part of the primary key of the table; UNI indicates that the column is part of the UNIQUE index; MUL indicates that a given value in the column is allowed to appear multiple times.
Default : Indicates whether the column has a default value, and if so, what is the value.
Extra : Indicates additional information related to a given column that can be obtained, such as AUTO_INCREMENT, etc.
SELECT 'Silicon Valley' as corporation, last_name FROM employees;

5. Filter data

insert image description here
grammar:

SELECT 字段1,字段2
FROM 表名
WHERE 过滤条件

Use the WHERE clause to filter out the rows that do not meet the condition
WHERE clause followed by the FROM clause

Example:

SELECT employee_id, last_name, job_id, department_id
FROM employees
WHERE department_id = 90 ;

insert image description here

#条件查询department_id=90  的值
SELECT  * FROM 
employees WHERE department_id=90 ;


#条件查询first_name='Steven'  的值
SELECT  * FROM 
employees WHERE first_name='Steven' ;


#条件查询first_name='Steven' 并department_id=90  两个条件都满足的内容 的值
SELECT  * FROM 
employees WHERE department_id=90 and first_name='Steven' ;

insert image description here
insert image description here

insert image description here

Guess you like

Origin blog.csdn.net/qq_42055933/article/details/131143323