select statement可以从表或视图中查询数据
syntax of the SELECT statement:
|
|
SELECT statement examples:
|
|
|
|
MySQL DISTINCT clause
|
|
MySQL DISTINCT example:
|
|
- If a column has NULL values and you use the DISTINCT clause for that column, MySQL keeps one NULL value and eliminates the other.
- use the DISTINCT clause with more than one column. In this case, MySQL uses the combination of all columns to determine the uniqueness of the row in the result set.
|
|
- use the GROUP BY clause in the SELECT statement without using aggregate functions, the GROUP BY clause behaves like the DISTINCT clause.
|
|
- use the DISTINCT clause with an aggregate function e.g., SUM, AVG, and COUNT, to remove duplicate rows before MySQL applies the aggregate function to the result set.
|
|
- use the DISTINCT clause with the LIMIT clause, MySQL stops searching immediately when it finds the number of unique rows specified in the LIMIT clause
|
|
WHERE clause
use WHERE clause to specify exact rows to select based on particular filter express or condition
|
|
the comparison operators that can use to form filtering expressions in the WHERE clause.
| Operator | Description |
|---|---|
| = | Equal to. You can use it with almost any data types. |
| <> or != | Not equal to. |
| < | Less than. You typically use it with numeric and date/time data types. |
| > | Greater than. |
| <= | Less than or equal to |
| >= | Greater than or equal to |
Note:
- some useful operators that you can use in the WHERE clause to form complex conditions:BETWEEN,LIKE,IN,IS NULL.
- The WHERE clause is used not only with the SELECT statement but also other SQL statements to filter rows such as DELETE and UPDATE.
ORDER BY clause
use the ORDER BY clause to sort the result set
|
|
ORDER BY sort by an expression example:
|
|
ORDER BY with customer sort order:
define custom sort order use FIELD() function
|
|
Natural Sorting with ORDER BY Clause:
|
|
the LENGTH function returns the length of a string
use the parentheses statement returns the customers who locate in the USA or France and have credit limit greater than 10000:
|
|
IN Operator
The IN operator allows you to determine if a specified value matches any one of a list or a subquery:
|
|
find out the offices that locate in the U.S. and France:
|
|
get offices that do not locate in USA and France, you use NOT IN in the WHERE clause:
|
|
MySQL IN with subquery:
|
|
BETWEEN Operator
use the BETWEEN operator in the WHERE clause of the SELECT, INSERT, UPDATE, and DELETE statements:
|
|
find products whose buy prices are within the ranges of $90 and $100:
|
|
get the orders whose required dates are from 01/01/2003 to 01/31/2003:
|
|