Basic SELECT statement - "MySQL database"

Hello fellow CSDN users, I haven’t updated Xiaoyalan’s MySQL database column for a long time. In the next period of time, Xiaoyalan will update the knowledge of MySQL database. Now, let’s get into today’s topic – the basic SELECT statement. ! ! !


SQL Overview

SQL language rules and specifications

Basic SELECT statement

Show table structure

Filter data


SQL Overview

SQL background knowledge

In 1946, the world's first computer was born. Today, the Internet developed through 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 arena, some are still in the ascendant, and some have seen their rise and fall. But in this vast fluctuation, there is one technology that has never disappeared, and is even getting stronger with time, and that is SQL.

45 years ago, 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 they are front-end engineers or back-end algorithm engineers, they will definitely deal with data, and they all need to know how to extract the data they want quickly and accurately. Not to mention data analysts, whose job is to work with data and compile different reports to guide business decisions.

SQL (Structured Query Language) is a database application language that uses a relational model and deals directly 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 represent the SQL standards promulgated in 1992 and 1999 respectively. The SQL language we use today still follows these standards.

Different database manufacturers support SQL statements, but each has its own unique content.

SQL language rankings

Since SQL joined the TIOBE programming language rankings, it has remained in the Top 10.

SQL Classification

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

  • 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, DROP, ALTER, etc.
  • DML (Data Manipulation Language), used to add, delete, update and query database records, and check data integrity. The main statement keywords include INSERT, DELETE, UPDATE, SELECT, etc. SELECT is the basis of SQL language and the most important.
  • DCL (Data Control Language) is used to define access rights and security levels of databases, tables, fields, and users. The main statement keywords include GRANT, REVOKE, COMMIT, ROLLBACK, SAVEPOINT, etc.

Because query statements are used very frequently, many people separate query statements into a single category: DQL (Data Query Language).

There are also separate COMMIT and ROLLBACK called TCL (Transaction Control Language, transaction control language).  


SQL language rules and specifications

Basic principles

SQL can be written in one line or multiple lines.

To improve readability, each clause is written on separate lines, and indentation is used when necessary. Each command ends with; or \g or \G

Keywords cannot be abbreviated or split into lines

About punctuation

        It must be ensured that all (), single quotes, and double quotes end in pairs

        You must use the half-width input method in English.

        String and date and time type data can be expressed using single quotes (' ')

        For column aliases, try to use double quotes (" "), and it is not recommended to omit as.

SQL case specifications (recommended to follow)

MySQL is case insensitive in Windows environment

MySQL is case-sensitive in Linux environment

        Database names, table names, table aliases, and variable names are strictly case-sensitive.

        Keywords, function names, column names (or field names), column aliases (field aliases) are case-insensitive.

It is recommended to adopt unified writing standards:

        Database names, table names, table aliases, field names, field aliases, etc. are all lowercase

        SQL keywords, function names, bind variables, etc. are all capitalized

Comment

Annotation structures in the following format can be used

Single-line comments: #comment text (MySQL-specific method)

Single-line comments: -- Comment text (-- must contain a space after it.)

Multi-line comments: /* comment text*/

 Naming rules

  • Database and table names must not exceed 30 characters, and variable names are limited to 29 characters.
  • Must contain only A–Z, a–z, 0–9, _63 characters in total
  • Do not include spaces in object names such as database names, table names, field names, etc.
  • In the same MySQL software, the database cannot have the same name; in the same library, the table cannot have the same name; in the same table, the 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 on using it, please use ` (emphasis mark) in the SQL statement.
  • Keep field names and types consistent. Be sure to ensure consistency when naming fields and assigning data types to them. If the data type is integer in one table, don't change it to character in another table.

Example:

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

#创建表格
#create table student info(...); #表名错误,因为表名有空格
create table student_info(...); 
#其中order使用``飘号,因为order和系统关键字或系统函数名等预定义标识符重名了
CREATE TABLE `order`();
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; #错误,如果字段别名中有空格,那么不能省略""

Data import instructions

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

mysql> source d:\mysqldb.sql

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)


Basic SELECT statement

SELECT...

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

SELECT ... FROM

grammar:

SELECT identifies which columns to select

FROM identifies which table to select from

Select all columns:

SELECT *

FROM   departments;

 

Generally speaking, it is best not to use the wildcard character '*' unless you need to use all field data in the table. Although using wildcards can save time typing query statements, obtaining unnecessary column data often reduces the efficiency of the query and the application used. The advantage of wildcards is that they can be used to obtain the required columns when their names are not known.

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;

 

SQL statements in MySQL are not case-sensitive, so the functions of SELECT and select are the same. However, many developers are accustomed to capitalizing 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.  

Column alias

Rename a column

Easy to calculate

Following the column name, you can also add the keyword AS between the column name and the alias. Use double quotes for the alias 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 understand the meaning of the name.

Example

SELECT last_name AS name, commission_pct comm

FROM   employees;

 

SELECT last_name "Name", salary*12 "Annual Salary"

FROM   employees;

 

 

Remove duplicate rows

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

SELECT department_id

FROM   employees;

 

Use the keyword DISTINCT in the SELECT statement to remove duplicate rows

SELECT DISTINCT department_id

FROM   employees;

 

Targeted at:

SELECT DISTINCT department_id,salary

FROM employees;

DISTINCT actually deduplicates all combinations of subsequent column names. You can see that the final result is 74 entries, because these 74 department IDs are different and all have the salary attribute value. If you want to see the different departments (department_id), you only need to write DISTINCT department_id, and there is no need to add other column names later.

Null values ​​participate in operations

 When any operator or column value encounters a null value, the result of the operation is null.

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

You must note here that in MySQL, a null value is not equal to an empty string. An empty string has a length of 0, while a null value has a length of nothing. Moreover, in MySQL, null values ​​take up space.

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)

in conclusion

We need to ensure that the fields, table names, etc. 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.

Query constant

SELECT queries can also query constants. That's right, it means adding a fixed constant column to the SELECT query results. The value of this column is specified by us, rather than dynamically taken from the data table.

You may ask why we still need to query constants?

The SELECT syntax in SQL does provide this function. Generally speaking, we only query data from one table. Usually there is no need to add a fixed constant column, but if we want to integrate different data sources, use a constant column as the table's Mark, you need to query the constant.

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

SELECT 'Silicon Valley' as corporation, last_name FROM employees;


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)

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

  • Field: Indicates the field name.
  • Type: Indicates the field type. Here barcode and goodsname are text types, and price is integer type.
  • Null: Indicates whether the column can store NULL values.
  • Key: Indicates whether the column is indexed. PRI means that the column is part of the table's primary key; UNI means that the column is part of the UNIQUE index; MUL means that a given value is allowed to appear multiple times in the column.
  • 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.

Filter data

grammar:

SELECT 字段1,字段2

FROM 表名

WHERE 过滤条件

Use the WHERE clause to filter out rows that do not meet the conditions

The WHERE clause follows the FROM clause

Example

SELECT employee_id, last_name, job_id, department_id

FROM   employees

WHERE department_id = 90 ;


 come on! ! !

Guess you like

Origin blog.csdn.net/weixin_74957752/article/details/132867620