Advanced MySQL table operations

Single-table queries

Simple Query

select * from table; See table all the data 
select field from table; single view field data 
select field, the field, from the field name; a plurality of view field data 
select distinct from the field name; check out of the fields to re-  select name, money * 12 from table; field may be four arithmetic  select concat (field, 'string', fields) from table; field name field string data as output fields long, can from the field name before adding a new or as new field name select concat_ws ( 'separator', 'string', fields, field) from simple field names name; the data string delimiter field separator field output in the form case is similar if select (case when conditions then results When name = 'Messi' then the concat (name, '_ The Best Player' ) the else the concat (name, '_great Player' ) End) AS NEW_NAME from table; if the field name is Messi, Messi is the output of the world's best players otherwise the output name is a good player

where constraints

select * from table where conditions

Range query 
    > <> = <= =! = / <> 
    BETWEEN A and B 
    in (1,2,3,4 ) is selected from n-1  Fuzzy queries  like  % arbitrary character representative of a percent sign of any length  'A%'  ' ING% '  '% a% ' _ represents an optionally an underscore character' A__ ' regexp' ^ a '' \ + D 'IS IS IS Not null IS Not null logical operations and or not

Group by group

Carried out in accordance with a high repetition rate field

How many in this field might be divided into how many groups

Deduplication can be done

Once the packet can not be on a specific piece of data to operate, and will always consider this group xxx

If we use the field as a unique basis for grouping, each a self-contained set of records, this grouping does not make sense 
the same value of a field between multiple records, the field is usually used as a basis for grouping

group_concat: only used for the final display, the other data can not be operated as an intermediate result

Alone GROUP BY keyword grouping 
    SELECT post FROM employee GROUP BY post; 
    Note: we follow the post field grouping, the field can only post select query, you want to get additional relevant information within a group, need the help function 

GROUP BY keyword and the GROUP_CONCAT () using a function with 
    SELECT post, GROUP_CONCAT (emp_name) FROM employee gROUP BY post; # accordance job packet, and view group members name of     the SELECT POST, the GROUP_CONCAT (the emp_name) AS emp_members the FROM Employee the gROUP BY POST; 
the gROUP BY polymerization use function with 
    select post, count (id) as count from employee group by post; # grouped according to the post, and see how many people in each group

polymerization

99.99% of cases are used, and grouped together 
if not together with the packet and, by default the entire table is a set of a 
COUNT (ID) / COUNT (* ) Count: each group of data corresponding to several 
max selecting the maximum value: the the maximum value of a field of the group 
min selecting the maximum value: in this group the minimum value of a field 
avg averaged 
sum summation value

Filter conditions having

Condition is a screening of the groups

WHERE HAVING not the same place and that the 
execution priority from high to low: WHERE> Group by> HAVING 
. 1 . Where occurs before the packet group by, and thus there can Where any field, but must not use the aggregate functions. 
2. Having occurs after a packet group by, Having thus can be used in the field of the packet, can not be taken directly to other fields, aggregate functions can be used

Sort order by inquiry

Field order by sort fields, default ascending 
order by field for the field in ascending order asc 
order by field desc descending order of the field 
order by one field, two fields 2 fields ascending 
order by field asc, desc Field 2 Field ascending are arranged in descending order of field 2

Limit the query to limit the number of records

1 . Display tab 
    limit m, n 
        represents the m + 1 starts, taking the n 
        limit 0, 6 represents six taken from a start 
        limit 6,6 represents from 7 to begin fetching six 
        limit 12,6 represents from 13 to begin fetching 6 Article 
        limit 18,6 represents from 19 starts to take 6
 2 from the former name n. 
    the default is 0 limit nm 
    with the order by, together with the 
limit n offset m: m from start + 1, taking the n

Multi-table query

Construction Table 
Create Table Department ( 
ID int, 
name VARCHAR ( 20 is ) 
); 

Create Table Employee ( 
ID int Primary Key AUTO_INCREMENT, 
name VARCHAR ( 20 is ), 
Sex enum ( ' MALE ' , ' FEMALE ' ) Not null default ' MALE ' , 
int Age, 
the dep_id int 
); 

insert data 
iNSERT INTO Department values 
( 200 is, ' technical ' ), 
( 201, ' HR ' ), 
(202,'销售'),
(203,'运营');

insert into employee(name,sex,age,dep_id) values
('egon','male',18,200),
('alex','female',48,201),
('wupeiqi','male',38,201),
('yuanhao','female',28,202),
( ' Liwenzhou ' , ' MALE ' , 18,200 ), 
( ' jingliyang ' , ' FEMALE ' , 18,204 ) 
;
Build tables and data preparation

Even table query

The two tables together, prior calculated Cartesian product of two tables, and then filtered according to the conditions given by the user

Turned out to be two tables, and now makes up a table, all operations are the same as the operation of a table

A cross-connect: NA any matching condition. Cartesian product is generated

Copy the code
MySQL> SELECT * from Employee, Department; 
+ ---- + ----------------------- + -------- + + ------ ------ - + ------ + -------------- + 
| the above mentioned id | name | Sex | Age | dep_id | the above mentioned id | name | 
+ ---- + ---- -------- + -------- + -------- + ------ + ------ + --------- + ----- 
|. 1 | Egon | MALE | 18 is | 200 is | 200 is | art | 
|. 1 | Egon | MALE | 18 is | 200 is | 201 | HR | 
|. 1 | Egon | MALE | 18 is | 200 is | 202 | sales | 
| 1 | Egon | MALE | 18 | 200 | 203 | operations | 
| 2 | alex | FEMALE | 48 | 201 | 200 | technology | 
| 2 | alex | FEMALE | 48 | 201 | 201 | human resources |  
| 2 | alex | female | 48 | 201 | 202 | sales |
| 2 | alex | female | 48 | 201 | 203 | operations | 
|. 3 | wupeiqi | MALE | 38 is | 201 | 200 is | art | 
|. 3 | wupeiqi | MALE | 38 is | 201 | 201 | HR | 
|. 3 | wupeiqi | male | 38 | 201 | 202 | sales | 
|. 3 | wupeiqi | MALE | 38 is | 201 | 203 | operator | 
|. 4 | yuanhao | FEMALE | 28 | 202 | 200 is | art | 
|. 4 | yuanhao | FEMALE | 28 | 202 | 201 | HR | 
|. 4 | yuanhao | FEMALE | 28 | 202 | 202 | sales | 
|. 4 | yuanhao | FEMALE | 28 | 202 | 203 | operator | 
|. 5 | liwenzhou | MALE | 18 is | 200 is | 200 is | technology | 
| 5 | liwenzhou | MALE | 18 | 200 | 201 | HR |
| 5 | liwenzhou | male | 18 | 200 | 202 | Sales | 
| 5 | liwenzhou | MALE | 18 | 200 | 203 | operations |
| 6 | jingliyang | female | 18 | 204 | 200 | Technology | 
| 6 | jingliyang | FEMALE | 18 | 204 | 201 | Human Resources | 
| 6 | jingliyang | FEMALE | 18 | 204 | 202 | Sales | 
| 6 | jingliyang | female | 18 | 204 | 203 | operations | 
+ ---- + -------- + ------------ + ------ + ---- ---- + ------ + -------------- +
Copy the code

2 the connection: only matching line connected

Copy the code
There are two tables to find parts, the equivalent of using the criteria to filter out results from the Cartesian product of the correct results 
department this department is not 204, so the employee table about 204 employees this information does not match up 
show only two tables match each other item not displayed does not match the other MySQL> SELECT employee.id, employee.name, employee.age, employee.sex in, department.name from the Join Department Employee Inner ON employee.dep_id = department.id; + ---- + + -------- + ------ + ----------- + -------------- | the above mentioned id | name | Age | Sex | name | + ----------- + ------ + ---- + -------- + ------------ - + |. 1 | Egon | 18 is | MALE | art | | 2 | Alex | 48 | FEMALE | HR | |. 3 | wupeiqi | 38 is | MALE | HR | |. 4 | yuanhao | 28 | FEMALE | sales | | 5 | liwenzhou | 18 | male | technology | + ---- ------ + + -------- + + ----------- + -------------- above sql Equivalent to mysql> select employee.id,employee.name,employee.age,employee.sex,department.name from employee,department where employee.dep_id=department.id;
Copy the code

3 external link Zhizuo connection: priority display all records from the left table

Copy the code
To the left table subject, that is, to find all the employee information, including of course no sector employees 
is essentially: increase the basal including the right connection on the left there is no result 
regardless of whether the match left on the table will display all content mysql> select employee.id, employee.name, department.name AS depart_name left from the Join Employee Department employee.dep_id ON = department.id; + ---- + ---- + ----------------------- + ---------- | the above mentioned id | name | depart_name | + ---- + ------------ + ------------- - + | 1 | Egon | technology | | 5 | liwenzhou | technology | | 2 | alex | human resources | | 3 | wupeiqi | human resources | | 4 | yuanhao | sales | | 6 | jingliyang | NULL | + --- - + ------------ + -------------- +
Copy the code

4 connected to the right hand outer link: all records displayed by priority right table

Copy the code
Subject to the right table, that is, to find information in all sectors, including the lack of staff departments 
essence is this: there is left no increase to the right of the results on the basis of connections, including 
on whether or not to match the right table will display all content mysql> select employee .id, employee.name, department.name AS depart_name right from the Join Employee Department employee.dep_id ON = department.id; + ------ + ----------- + ---- + ---------- | the above mentioned id | name | depart_name | + ------ + ----------- + ------------ - + | 1 | Egon | technology | | 2 | alex | human resources | | 3 | wupeiqi | human resources | | 4 | yuanhao | sales | | 5 | liwenzhou | technology | | NULL | NULL | operations | + - ---- + ----------- + -------------- +
Copy the code

5 full outer join: All records about two tables

Copy the code
Full outer join: including increasing the basic connection on the left has the right results to the right and not the left there is no 
Note: mysql does not support full outer join full JOIN 
stressed: mysql this way can be used indirectly to achieve full outer joins 
select * from employee ON = employee.dep_id the Join Department left department.id 
Union 
SELECT * from the Join Department Employee right employee.dep_id ON = department.id 
; 
see results 
+ ------ + ------------ -------- + -------- + ------ + + ------ + -------------- + 
| the above mentioned id | name | Sex | Age | dep_id | the above mentioned id | name | 
+ ------ + ------------ + -------- + ------ + + ------ + -------------- + -------- 
|. 1 | Egon | MALE | 18 is | 200 is | 200 is | art | 
|. 5 | liwenzhou | male | 18 | 200 | 200 | technology | 
| 2 | alex | FEMALE | 48 | 201 | 201 | HR |
| 3 | wupeiqi | male | 38 | 201 | 201 | HR |
| 4 | yuanhao | female | 28 | 202 | 202 | Sales | 
|. 6 | jingliyang | FEMALE | 18 is | 204 | NULL | NULL | 
| NULL | NULL | NULL | NULL | NULL | 203 | operator | 
+ ---- - + ------------ + -------- + -------- + ------ + ------ + - ------------ + 

Note the difference between union and the union all: union will remove the same record
Copy the code

Eligible join query

Copy the code
Example 1: connected within query tables employee and department, and employee age field value in the table must be greater than 25, that is, to find older than 25 years of department employees and staff where 
select employee.name, department.name from employee inner department the Join 
    ON employee.dep_id = department.id 
    WHERE age> 25; 

example 2: query connected within employee and department tables and displayed in ascending order of the age field 
select employee.id, employee.name, employee.age, department Employee from .name, Department 
    WHERE employee.dep_id = department.id 
    and Age> 25 
    Order by Age ASC;
Copy the code

Subqueries

Sub-query is a query nested within another query statement

The inner query results statement, the query may provide the conditions for the outer query

Subqueries can include in, not in, exists and comparison operators and other keywords

1 IN keyword with a subquery

Copy the code
Queries average age of 25-year-old department name 
the SELECT the above mentioned id, name from Department 
    the WHERE the above mentioned id in 
        (the SELECT dep_id from the Employee Group by dep_id the HAVING AVG (Age)> 25); 

see technical department employee name 
the SELECT name from the Employee 
    the WHERE dep_id in 
        (the SELECT id from department where name = 'technology'); 

see less than one person's department name (subquery get is someone's department the above mentioned id) 
the SELECT name from the above mentioned id not in the WHERE department (dep_id the SELECT DISTINCT from the Employee);
Copy the code

2 subqueries with comparison operators

Copy the code
Comparison operators:! =, =,>,> =, <, <=, <> 
Query is greater than the average age for all employees name and age 
mysql> select name, age from emp where age> (select avg (age) from EMP); 
+ --------- + ------ + 
| name | Age | 
+ --------- + ------ + 
| Alex | 48 | 
| wupeiqi | 38 | 
+ --------- + ------ + 
2 rows in the SET (0.00 sec) 


query is greater than the average age of employees within the department name, age 
select t1.name, t1.age from T1 EMP 
Inner the Join 
(SELECT the dep_id, AVG (Age) avg_age from Group by the dep_id EMP) T2 
ON = t2.dep_id t1.dep_id 
WHERE t1.age> t2.avg_age;
Copy the code

3 with keyword EXISTS subquery

Off EXISTS word indicates the presence of the cross key. When using the EXISTS keyword, the inner query does not return records query.
But return a true or false value. True or False
when returns True, the outer query query; when the return value is False, the outer query is not a query

Copy the code
department表中存在dept_id=203,Ture
mysql> select * from employee
    ->     where exists
    ->         (select id from department where id=200);
+----+------------+--------+------+--------+
| id | name       | sex    | age  | dep_id |
+----+------------+--------+------+--------+
|  1 | egon       | male   |   18 |    200 |
|  2 | alex       | female |   48 |    201 |
|  3 | wupeiqi    | male   |   38 |    201 |
|  4 | yuanhao    | female |   28 |    202 |
|  5 | liwenzhou  | male   |   18 |    200 |
|  6 | jingliyang | female |   18 |    204 |
+----+------------+--------+------+--------+

department表中存在dept_id=205,False
mysql> select * from employee
    ->     where exists
    ->         (select id from department where id=204);
Empty set (0.00 sec)
Copy the code

Guess you like

Origin www.cnblogs.com/biulo/p/11291231.html
Recommended