DQL - MySQL
1. Basic Query SQL syntax
Get all of the data
sql
SELECT <field_name | *> FROM <table_name>;*means everything in a tablefield_namecan be multiple, seperated by,
Get data based on condition
- By using
WHEREto define a condition, tofilterthe data we want
sql
SELECT <field_name | *>
FROM <table_name>
WHERE <condition>;<condition>can have multiple.- By using
AND,ORto join the condition / requirments.
2. GROUP BY (分组聚合 (Data Aggregation) )
Syntax
sql
SELECT <field>, <Aggregation_Function(field)>
FROM <table_name>
WHERE <condition>
GROUP BY <field_name>;- For
<field>, <Aggregation_Function(field)>will return a table with label + data of<field>, <Aggregation_Function(field)> - Ex:
name, AVG(age)will have 2 field will returned, which isname, avg(age) - IF
GROUP BYis applied, it will render thegroup-by-field to first, then<field>, <Aggregation_Function(field)>.
Aggregation / polymerization function
| Aggregation / polymerization function 聚合函数 | Usage |
|---|---|
SUM(field) | Get SUM of the value |
AVG(field) | Get the AVERAGE number value |
MIN(field) | Get MINIMUM value |
MAX(field) | Get MAXIMUM value |
COUNT(field / *) | Get AMOUNT of record |
3. ORDER BY [ASC / DESC]
sql
SELECT <field>, <Aggregation_Function(field)>
FROM <table_name>
WHERE <condition>
GROUP BY <field_name>
ORDER BY <DESC | ASC>;ASCmeans ascending (from 0 -> n), it's also default valueDESCmeans descending (from n -> 0)
4. LIMIT
- Use for pagination or limit the data returning from query.
sql
SELECT <field>, <Aggregation_Function(field)>
FROM <table_name>
WHERE <condition>
GROUP BY <field_name>
ORDER BY <DESC | ASC>
LIMIT n[, m];LIMITcan either isnumberorrange.- Ex:
LIMIT 5, limiting 5 records will be retuned. LIMIT 10, 5, means from 10th records of data, take 5 records after 10 (11, 12, 13, 14, 15)