Table of contents
Foreword:
The table operated in the example is the actor table in the Sakila sample database, and the table structure is as follows
Sakila installation tutorial: Installing the Sakila database
SELECT syntax
SELECT columns_list FROM table_name;
That is, the SELECT column name and the FROM table name; (to develop good code habits, it is recommended that all keywords be capitalized)
The actual semantics of the SELECT statement is:
FROM table_name SELECT columns_list
, that is, to retrieve certain columns of data from a certain table.SELECT
When MySQL parses a statement, it first evaluatesFROM
the clause, and then evaluatesSELECT
the clause.example
single field query
SELECT last_name FROM actor;
This line of code means: Find the last_name column in the actor
multiple field query
Separate multiple fields with commas in multi-field query
SELECT first_name,last_name FROM actor;
query all fields
SELECT * FROM actor;
Use * to indicate all fields
Of course, you can choose to write all the fields directly and separate them with commas
So
column_name
what's the difference between using * and ? Generally speaking, the performance of the two is about the same. In terms of differences, there are the following differences:1. Write clear fields, it is easier to understand the query intent of your SQL
2. Some large fields are not suitable for direct query, because direct query will take up more overhead
3.SELECT *
More suitable for use in command line or test scenariosbut in some cases
column_name会比*更快,可以看下这篇文章https://www.cnblogs.com/katechun/p/9498231.html
SELECT without FROM
In MySQL, in some cases the data you want to retrieve does not exist in any table, then you can omit the FROM clause,
for example
Query system time
SELECT NOW();
Numeral Calculations
SELECT 1+2;
virtual table dual
That is, when there is no FROM clause, you can choose to still add FROM dual
SELECT NOW() FROM dual; SELECT 1+2 FROM dual;
This dual does not actually exist, and the query results of this statement and the above statement are the same, just to make the code alignment more beautiful
WHERE statement
The role of the where statement is to filter the results, which is very commonly used
SELECT columns_list FROM table_name WHERE query_condition;
Among them
query_condition
is the query condition, and its result is a Boolean value, which may beTRUE
,FALSE
orUNKNOWN
. Ultimately,SELECT
the result set returned by the statement isTRUE
the record that meets the query condition and the result is .
NOT
Query conditions are generally used to compare whether a field matches a value, or a combination of one or more expressions using AND, OR, and logical operators.In addition to being used in
SELECT
statements,WHERE
clauses can also be used in UPDATE and DELETE statements to specify which rows to update or delete.example
=
SELECT * FROM actor WHERE last_name = 'ALLEN';
That is to say, query all the columns in the actor, and filter out all the results of last_name = 'ALLEN' on this result
AND
AND can combine multiple conditions, that is, 'and' in mathematics, all true is true, one false is false
SELECT * FROM actor WHERE last_name = 'DAVIS' AND first_name = 'SUSAN';
Filter out the entries in the table where
last_name
the value isDAVIS
andfirst_name
the value is SUSAN
OR
It is equivalent to "or", one true is true, all false is false
SELECT * FROM actor WHERE last_name = 'DAVIS' OR first_name = 'SUSAN';
That is to say, filter out entries
last_name
whose value isDAVIS
, orfirst_name
whose value is SUSAN
comparison operator
The = we exemplified above is one of the comparison operators, here are other comparison operators
At this point, we found that the original function of SELECT is to query by column, while WHERE restricts rows
AND
AND
AND
operator is a binary logical operator used to combine two operands. The result returns true only if both operands are true, else it returns false orNULL
. There is no Boolean type in MySQL,AND
the operation result is1
,0
, orNULL
.Here 1 means not 0
The logic of AND is in mathematics. All truths (that is, 1) are true, and one false is false (that is, 0). However, a NULL is introduced here to make the result of this operation not very easy to remember. Let's look at the table below , is the operation result table
Here I introduce my own memory method, assuming "level" 0>NULL>1, if the two operands are the same, then the result is the result of the operand, if they are different, it is the result of a higher level
When we observe the results of these three lines of instructions, we can find that the result of the WHERE filter of the last two statements is empty, that is, there is no result.
Because the result of AND is 0 or NULL, and WHERE will only filter out entries that are TRUE or 1
OR
OR and AND are both binocular operators, there is no TRUE, and FALSE is replaced by 1 0 NULL
The logic of OR is "or", one true and all true, all false is false
According to the memory method above, we can think that the level relationship is 1>NULL>0
operator precedence
When a combined expression contains both
AND
andOR
operators, MySQL uses operator precedence to determine the order in which operators are evaluated. MySQL evaluates operators with higher precedence first.Since
AND
operators have higher precedence than operatorsOR
, MySQL evaluates operatorsAND
beforeOR
If you need to adjust the order of operations, you can use parentheses
IN
We directly use this line of command as an example
SELECT * FROM actor WHERE first_name IN ('SUSAN')
first_name IN ('SUSAN')
When the column on the left does contain the parameters in the brackets on the right, it is 1 (can be filtered by WHERE)
Multiple values are allowed in parentheses, separated by commas
Essentially equivalent to multiple OR in conjunction
for example
SELECT * FROM table WHERE name IN ('ZHANGSAN','LISI','WANGWU')
is equivalent to
SELECT * FROM table WHERE name = 'ZHANGSAN' OR name = 'LISI' OR name = 'WANGWU'
Therefore, the relationship between the result of 1 0 NULL is consistent with OR, but if the left operand is NULL, no matter what is behind it, it will be NULL
NOT IN
It is the negation of IN, so the result is the opposite of IN.
BETWEEN
expression BETWEEN min AND max
expression is a column, a field column, an operation result column, or a function return.
min smaller value
max max value
AND fixed collocation conjunctions
The meaning of this string of codes is the line between min and max in expression
BETWEEN is equivalent to expression >= min AND expression <= max
NOT BETWEEN
There is not much explanation, it is the row that is not between min and max in the expression of the opposite value of BETWEEN
LIKE
LIKE
operator is a binary comparison operator that takes two operands.LIKE
The operator syntax is as follows:expression LIKE pattern
expression is the column name or an expression for the column name
pattern is a string pattern. MySQL string patterns support two wildcard characters:
%
and_
.% matches zero or more characters
_ matches a character
For example, ab% is a string beginning with ab
And ab_ is a string that starts with ab and has a string length of 3 (because _ can only match one)
So let's consider this situation. What if we want to match a string starting with %a? If direct LIKE %a is obviously not what we want
Answer: To match wildcards, you can use
\
escape characters, such as\%
and\_
.Example:
NOT LIKE does not match
EXISTS
grammar:
SELECT column_name FROM table_name WHERE EXISTS(subquery);
The role of EXISTS is to judge whether the subquery statement of subquery (for example, name = 'Zhang San' is not a subquery SELECT statement) has returned rows. If there is at least one row, the calculation
EXISTS
result isTRUE
, otherwise the calculation result isFALSE
.EXISTS
When operating, once the subquery finds a matching row,EXISTS
the operation returns. And as long as the operation result after WHERE is TRUE, the row will be selectedExample:
When retrieving
language
each row of the table , as long asfilm
there is a row of data in the table with the same valuelanguage_id
,EXISTS
it is returnedTRUE
. Then go tolanguage
the next row of the table until all rows have been retrieved, and then returnlanguage
all matching rows in the table. (This language goes down every line and every line, and all the data of the film is placed here)
ORDER BY
You can sort the results of SELECT, and you can specify descending order and ascending order
SELECT column1, column2, ... FROM table_name [WHERE clause] ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;
ASC
Represents ascending order andDESC
descending order.- When not specified
[ASC|DESC]
, the default isASC
. That is, the default is to sort by the specified field in ascending order.- When multiple columns are specified, sort by the preceding field first, and then sort by the following field.
What does it mean to sort first and then in what order? It's actually very simple
Let's look at an example
SELECT actor_id, first_name, last_name FROM actor ORDER BY last_name, first_name;
First in ascending order by last_name and then in ascending order by first
Look at this result When the last_name field has the same size, sort according to the size of the first_name field
The size of this field does not mean the length. Comparing two fields starts from the first letter and compares to the end, just like comparing 159 and 63
As long as the front bit is bigger than the back bit, you don’t need to look at the back (for example, AA is bigger than ABCDEFG)
LIMIT
Can be used to limit
SELECT
the number of rows returned by a statementLIMIT [offset,] row_count;
LIMIT row_count OFFSET offset;
These two lines of code are equivalent
offset is the offset (from the first few lines)
row_count (a total of several rows)
LIMIT 5 OFFSET 3 is to output a total of five lines starting from the fourth line
No matter where you write it, the ORDER BY and LIMIT statements do not need to be included in the WHERE
If you want to use WHERE ORDER BY and LIMIT in combination, pay attention to the order
First WHERE then ORDER BY and finally LIMIT
DISTINCT
SELECT DISTINCT columns_list FROM table_name
It is deduplication. The SELECT statement with the DISTINCT keyword will deduplicate according to the columns_list and then output the result
If there are multiple columns_lists, they are not deduplicated according to the columns_list, but between multiple columns_lists.
If there is such a line of code
SELECT DISTINCT last_name,first_name FROM actor;
Its meaning is to remove the result of last_name and first_name