Full query syntax for the database
In daily work, it is often necessary to deal with the database. Although most of the time it is a simple query or a query method encapsulated by the framework, it is still necessary to have a deeper understanding of the complete query syntax of the database.
Database complete query syntax framework
select [distinct] field 1 [as alias], ..., field n [as alias] from [library name.] table name [ where constraints group by group by having filter order by field to sort by limit limit the number of bars displayed ]; Note: 1. All fields in the lookup table are represented by * (select * from ...) 2. The writing rules of conditions are written in strict accordance with the grammatical order, which can be defaulted, but cannot be wrongly ordered 3. The flow of constraints: from -> where -> group by -> having -> distinct -> order by -> limit 4. Fields can be aliased 5. The field can be directly operated select age + 1 'new_age' from emp; 6. The conditions after grouping can use aggregate functions ''' ''' 3. Pseudo code parsing process def from(): return "query file" def where(file): return "Result after condition filtering" def group_by(res): return "Grouped result" def having(res): return "Result after filtering again" def distinct(res): return "Result after deduplication" def order_by(res): return "sorted result" def limit(res): return "Result after limit number" def select(from=from, where=null, ..., limit=null): file = from() res = where(file) if where else file res = group_by(res) if group_by else res ... res = limit(res) if limit else res return res select(where=where, group_by=group_by)
-
Basic grammar
- select field_name from Table_name >>> single field query in the table
- select * from Table_name >>> query all fields in the table
-
where condition
- Conditions can be various operations and regular matching
1. Comparison operators ``` = < > <= >= != ``` ``` select * from emp where area!="上海"; ``` 2. Interval operator between 10 and 20 # means between 10-20 in (10,20,30) # means 10,20 or 30 ``` select * from emp where id between 3 and 5; # [3, 5], closed interval, including 3 and 5 ``` 3. Logical Operators and or not ``` select * from emp where area='Shandong' and port='Jinan'; mysql> select * from emp where area='Shandong' and port='Jinan'; +----+-------+--------+------+--------+--------+--------+-----------+ | id | name | gender | age | salary | area | port | dep | +----+-------+--------+------+--------+--------+--------+-----------+ | 2 | owen | Male | 38 | 9.4 | Shandong | Jinan | | 10 | kevin | Male | 36 | 5.8 | Shandong | Jinan | +----+-------+--------+------+--------+--------+--------+-----------+ 2 rows in set (0.00 sec) ``` 4. Similarity operator (like) Underscore or % can be used for fuzzy matching ``` select * from emp where name like '__en%'; # 匹配出Owen mysql> select * from emp where name like '__en%'; +----+------+--------+------+--------+--------+--------+-----------+ | id | name | gender | age | salary | area | port | dep | +----+------+--------+------+--------+--------+--------+-----------+ | 7 | owen | Male | 28 | 8.8 | Anhui | Xuancheng | +----+------+--------+------+--------+--------+--------+-----------+ 1 row in set (0.00 sec) ``` 5. Regular matching (regexp) - Due to the limited range of fuzzy matching done by like, the number can be fuzzy, but the type cannot be fuzzy - ------ Regular can complete fuzzy matching of type and number (only support some grammars) ```python select * from emp where name regexp '.*[0-9]+.*'; # match records with numbers in their names mysql> select * from emp where name regexp '.*[0-9]+.*'; +----+------+--------+------+--------+--------+--------+-----------+ | id | name | gender | age | salary | area | port | dep | +----+------+--------+------+--------+--------+--------+-----------+ | 13 | san1 | Male | 30 | 6 | Shanghai | Pudong | | 14 | san2 | Male | 30 | 6 | Shanghai | Puxi | +----+------+--------+------+--------+--------+--------+-----------+ 2 rows in set (0.00 sec) ```
-
group by group by
- Group records by their field commonality
- After grouping, the fields can be processed by aggregation functions
___Aggregate Functions___ max(): maximum value min(): minimum value avg(): average sum(): and count(): count group_concat(): Field concatenation in the group, used to view other fields
in the group___example___
# eg1
# Average salary of each departmentselect
dep, avg(salary) 'Average salary' from emp group by dep;
mysql> select dep, avg(salary) 'average salary' from emp group by dep;
+-----------+------------------ -+
| dep | Average Salary |
+----------+-------------------+
| Consulting Department | 6.250000059604645 | |
HR Department | 5.400000027247837 |
| Technical Department | 5.850000023841858 |
+-----------+-------------------+
3 rows in set (0.00 sec )
# eg:2
# Who are in each department
select dep, group_concat(name) 'name' from emp group by dep;
mysql> select dep,group_concat(name) 'name' from emp group by dep;
+-----------+------------------- --------------------+
| dep | name |
+-----------+----------- ----------------------------+
| Consulting Department | san1,san,ying,zero |
| Technical Department | san2,kevin,owen ,jiboy,tank,jerry,engo |
| Human Resources | monkey,yangsir |
+------------+------------------- --------------------+
3 rows in set (0.04 sec)
# eg3
# The highest salary attached to the teaching department in each gender
select max(salary) 'maximum salary', gender from emp where dep='teaching department' group by gender;
-
having filtered
- Further filter the results of where and group by processing to get the data we want
1. Average salary by department select dep, avg(salary) 'average salary' from emp group by dep; 2. Departments with an average salary greater than 6w (average salary of departments and departments) Solution: Group by dep, and use avg(salary) as the judgment condition (screening) select dep, avg(salary) 'average salary' from emp group by dep having avg(salary) > 6; # Summary: having completes filtering through aggregate function results select max(salary) from emp having max(salary) > 9.4; # Although group by is not explicitly written, the aggregate function is used in having, so the query considers the entire table as a default large table, so the query field can only be the result of the aggregate function
-
order by sort
- Sort the filter results in ascending or descending order (default is ascending)
- Ascending: asc ; Descending: desc
# eg: order by age desc => Descending by age select * from emp order by age desc; # need: # Sort the departments in descending order of the average salary of the department select dep, avg(salary) from emp group by dep order by avg(salary) desc;
-
limit limit
- The number of rows to display the final data result, can only be used with numbers
# limit 1: Only one row of data can be displayed # limit 6,5: Display 5 pieces of data starting from line 6+1 (index starts from 0) select * from emp limit 1; select * from emp limit 6,5; # need: # Get a message from the highest paid person select * from emp order by salary desc limit 1;
Reprinted in: https://www.cnblogs.com/whnbky/p/11586887.html