day 44 single-table queries, multi-table queries, subqueries

Single-table queries

By:
INSERT [INTO]
[database name.] Table [(1 field [, ..., field n-])]
values
(data 1 [, ..., n-data]) [, ..., (data 1 [, ..., n-data])];

Delete:
the Delete from [. Database Name] table [condition];

Change:
UPDATA [database name.] Table set field value 1 = 1 [, ..., n = the value of the field n] [Condition];

Zha:
SELECT [DISTINCT] 1 Field [[AS] alias 1], ..., field n [[as] Alias n] from [database name.] Table [Condition];
"" "

# Condition: from, where, group by, having, distinct, order by, limit => results after layers of screening
# Note: a query, you can have a variety of screening conditions, the conditions of the order must be carried out stepwise selection in the order above , distinct little special (writing position), the kind of conditions can be incomplete
# can be deleted, but not out of order

 

 

# Deduplication: distinct

mysql>:
create table t1(
  id int,
  x int,
  y int
  );

mysql>: insert into t1 values(1, 1, 1), (2, 1, 2), (3, 2, 2), (4, 2, 2);

mysql>: select distinct * from t1; # all data

mysql>: select distinct x, y from t1; # 1,1 1,2 2,2 Results

mysql>: select distinct y from t1; # 12 Results

# Summary: distinct participate in all fields of inquiry, the overall de-emphasis (the value of all the fields of the same investigation, was considered to be duplicate data)

 

data preparation

CREATE TABLE `emp` (
`id` int(0) NOT NULL AUTO_INCREMENT,
`name` varchar(10) NOT NULL,
`gender` enum('男','女','未知') NULL DEFAULT '未知',
`age` int(0) NULL DEFAULT 0,
`salary` float NULL DEFAULT 0,
`area` varchar(20) NULL DEFAULT '中国',
`port` varchar(20) DEFAULT '未知',
`dep` varchar(20),
PRIMARY KEY (`id`)
);

The INTO `emp` the VALUES the INSERT
(. 1, 'yangsir', 'M', 42, 10.5, 'Shanghai', 'Pudong', 'unit faculty'),
(2 'Engo', 'M', 38, 9.4 'Shandong', 'Jinan', 'Education Department'),
(3, 'Jerry', 'female', 30, 3.0, 'Jiangsu Province', 'Zhangjiagang', 'Education Department'),
(4, 'Tank' 'female', 28, 2.4, 'Guangzhou', 'Guangdong', 'Education Department'),
(5 'jiboy', 'male', 28, 2.4, 'Jiangsu Province', 'Suzhou', 'Education Ministry' ),
(6, 'ZERO', 'male', 18, 8.8, 'China', 'Huangpu', 'consulting'),
(7, 'Owen', 'male', 18, 8.8, 'Anhui' 'Xuancheng', 'Education Department'),
(8 'Jason', 'male', 28, 9.8, 'Anhui', 'lake', 'Education Department'),
(9, 'ying', 'female' ,36, 1.2, 'Anhui', 'Wuhu', 'Consulting'),
(10, 'Kevin', 'male', 36, 5.8, 'Shandong', 'Jinan', 'Education Department'),
(11, 'monkey', 'female', 28, 1.2, 'Shandong', 'Qingdao', 'faculty Department'),
(12, 'San', 'male', 30, 9.0, 'Shanghai', 'Pudong' 'consulting'),
(13, 'SAN1', 'male', 30, 6.0, 'Shanghai', 'Pudong', 'consulting'),0, 'Shanghai', 'Pudong', 'Consulting'),0, 'Shanghai', 'Pudong', 'Consulting'),
(14, 'san2', 'male', 30, 6.0, 'Shanghai', 'Puxi', 'Education Department'),
(15, 'ruakei', 'female', 67, 2.501, 'Shanghai', 'Lujiazui ', 'Education Department');

 

# Commonly used functions

Stitching: concat () | concat_ws ()
case: upper () | lower ()
floating point operations: ceil () | floor () | round ()
Integer: direct operation

MySQL>: the SELECT name, Area, Port from emp;
mysql>: select name as the name, concat (area, '-' , port) address from emp; # Shanghai - Pudong
mysql>: select name as the name, concat_ws ( '- ', area, port, dep) information from emp; # Shanghai - Pudong - Faculty Department

mysql>: select upper (name) name uppercase, lower (name) names lowercase from emp;

mysql>: select id, salary, ceil upper (salary) salary, floor (salary) under Payroll, round (salary) into the salary from emp;

mysql>: select name names, age older ages, age + 1 New Age from emp;

 

# Condition: where

# Import coordinate operation of multiple conditions: where odd [group by sector having the average salary] order by [average] salary limit 1

mysql>: select * from emp where id <5 limit 1; # normal
mysql>: select * from emp limit 1 where id <5; # abnormal, disordered condition

# Judgment rule
"" "
more in line with:> | <|> = | <= | = | =!
Range in line: between the beginning and end | in (custom containers)
logic accord: and | or | not
similar accord: like _ |%
regular accord: regexp regular grammar
"" "
MySQL>: the SELECT * from emp the WHERE salary> 5;
MySQL>: the SELECT * from emp the WHERE the above mentioned id% 2 = 0;

mysql>: select * from emp where salary between 6 and 9;

mysql>: select * from emp where id in(1, 3, 7, 20);

# _o 某o | __o 某某o | _o% 某o* (*是0~n个任意字符) | %o% *o*
mysql>: select * from emp where name like '%o%';
mysql>: select * from emp where name like '_o%';
mysql>: select * from emp where name like '___o%';

# Sql support only part of the regular syntax
mysql>: select * from emp where name regexp '. * \ D'; # does not support \ d represents the number that \ d is an ordinary string
mysql>: select * from emp where name regexp ' . * [0-9] '; # support [] syntax

 

# Grouping and filtering: group by | having

where与having

# Appearance: in the absence of a packet, where the having the same results
# Key: HAVING polymerization results can be screened
MySQL>: SELECT * WHERE EMP from the salary>. 5;
MySQL>: SELECT * from EMP HAVING the salary>. 5;

mysql>: select * from emp where id in (5, 10, 15, 20);
mysql>: select * from emp having id in (5, 10, 15, 20);

 

Aggregate function

max (): maximum value
min (): minimum value
avg (): average
sum (): and
count (): count
group_concat (): the group field splicing, to view other fields within the group

Queries group by group

# 修改my.ini配置重启mysql服务
sql_mode=ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

# In sql_mode ONLY_FULL_GROUP_BY no restrictions, it can do, but the result does not make sense
# ONLY_FULL_GROUP_BY have limitations, being given
mysql>: select * from emp group by dep;

# After grouping the data in Table consideration is not a single record, because each packet contains more than one record, referring to the grouping field, for many records in each group of unitary
# eg: grouped by departments, each department who has the highest salary, the minimum salary, average salary, set in a total number of people

# Unify the multiple data processing, this approach is called polymeric
# each department who has the highest salary, the minimum salary, average salary are called polymerization results - aggregate function results of operations
# Note: participation in group field, is attributed to polymerization results

MySQL>:
the SELECT
  DEP department,
  GROUP_CONCAT (name) member,
  max (salary) highest salary,
  min (salary) minimum wage,
  AVG (salary) average salary,
  SUM (salary) of the total payroll,
  COUNT (Gender) number
from emp group by dep;

MySQL>: the SELECT
      DEP department,
      max (Age) maximum age
    from emp group by dep;

# Summary: After the grouping, the polymerization results can only query packet fields aggregate functions and operations

 

having grouped

MySQL>:
the SELECT
DEP department,
GROUP_CONCAT (name) member,
max (salary) highest salary,
min (salary) minimum wage,
AVG (salary) average salary,
SUM (salary) of the total payroll,
COUNT (Gender) number
from emp group by dep;

# Minimum wage is less than 2
MySQL>:
the SELECT
DEP department,
GROUP_CONCAT (name) member,
max (salary) highest salary,
min (salary) minimum wage,
AVG (salary) average salary,
SUM (salary) of the total payroll,
COUNT (Gender) number
from emp group by dep having min ( salary) <2;

# Having polymerization results can then be screened, where not

 

Sort #

Collation

# Order by the primary sort field [asc | desc], secondary sort field 1 [asc | desc], ... secondary sort field n [asc | desc]

 

Ungrouped state

mysql>: select * from emp;

# Ascending order by age
MySQL>: the Order by the SELECT * from emp Age asc;
# descending order according to salary
mysql>: select * from emp order by salary desc;

# Descending order according to salary, if the same, then aged descending
MySQL>: the SELECT * from emp the Order by salary desc, Age desc;
# descending order according to age, if the same, then pay descending
mysql>: select * from emp order by age desc , salary desc;

 

Grouped state

MySQL>:
the SELECT
  DEP department,
  GROUP_CONCAT (name) member,
  max (salary) highest salary,
  min (salary) minimum wage,
  AVG (salary) average salary,
  SUM (salary) of the total payroll,
  COUNT (Gender) number
from emp group by dep;

# Highest salary in descending
MySQL:
the SELECT
  DEP department,
  GROUP_CONCAT (name) member,
  max (salary) highest salary,
  min (salary) minimum wage,
  AVG (salary) average salary,
  SUM (salary) of the total payroll,
  COUNT (Gender) number
from Group by DEP emp
the Order by the highest salary desc;

 

# Restrictions limit

# Syntax: limit the Number | offset limit, the Number
mysql>: select name, salary from emp where salary <8 order by salary desc limit 1;

mysql>: select * from emp limit 5,3; # offset recording to satisfy the condition of 5, then the query 3

 

 

Even table query

#connection

# Connection: There will be multiple tables linked by association (linked on the line, not necessarily a foreign key) field, to connect, a large table parameter
# even-table query: query on the basis of a large table, you call it even as table query

# Table with the table in establishing a connection there are four: internal connections, connect the left and right connections, fully connected

 

Many data preparation

mysql>: create database db3;
mysql>: use db3;

MySQL>:
Create Table DEP (
  ID int Primary Key AUTO_INCREMENT,
  name VARCHAR (16),
  Work VARCHAR (16)
);
Create Table EMP (
  ID int Primary Key AUTO_INCREMENT,
  name VARCHAR (16),
  the salary a float,
  the dep_id int
);
INSERT into dep values (1, 'marketing', 'sales'), (2, 'Education Department', 'teaching'), (3, 'management Department', 'car');
INSERT INTO emp (name, salary, dep_id) values ( 'egon', 3.0, 2), ( 'yanghuhu', 2.0, 2), ( 'sanjiang', 10.0, 1), ( 'owen', 88888.0, 2), ( 'liujie', 8.0, 1), ( 'yingjie', 1.2, 0);

 

Cartesian Product

# Cartesian product: set X {a, b} * Y {o, p, q} => Z {{a, o}, {a, p}, {a, q}, {b, o}, { b, p}, {b, q}}

mysql>: select * from emp, dep;

# Summary: all the permutations and combinations of the two tables of records, the data is not of value

 

En #

Keyword #: Inner the Join ON
# syntax:.. From A table TABLE inner join B on A = B Table relevance field table associated field

mysql>:
select
emp.id,emp.name,salary,dep.name,work
from emp inner join dep on emp.dep_id = dep.id
order by emp.id;

# Summary: keep only two tables of data associated

 

# Left connection

# Keywords: left join on
# syntax:.. From the left table left join the table associated with the right table on the left field = fields associated with the right table

mysql>:
select
  emp.id,emp.name,salary,dep.name,work
from emp left join dep on emp.dep_id = dep.id
order by emp.id;

# Summary: retain all data left table, right table there is a direct link corresponding data table shows, there is no correspondence between filling empty

 

# Right connection

Keyword #: right ON the Join
# Syntax: from A Table Table right join B on A = B Table relevance field table associated field.

mysql>:
select
  emp.id,emp.name,salary,dep.name,work
from emp right join dep on emp.dep_id = dep.id
order by emp.id;

# Summary: the right to retain all the data tables, the left table has directly connected to the corresponding data table shows, there is no correspondence between filling empty

 

Left and right can be transformed into each other

mysql>:
select
  emp.id,emp.name,salary,dep.name,work
from emp right join dep on emp.dep_id = dep.id
order by emp.id;

mysql>:
select
  emp.id,emp.name,salary,dep.name,work
from dep left join emp on emp.dep_id = dep.id
order by emp.id;

# Summary: replace what position around the table, replace the corresponding left and right connection key, same result

 

# Fully connected

mysql>:
select
  emp.id,emp.name,salary,dep.name,work
from emp left join dep on emp.dep_id = dep.id

union

select
  emp.id,emp.name,salary,dep.name,work
from emp right join dep on emp.dep_id = dep.id

order by id;

# Summary: Left table Right table data is retained, there is another correspondence between the normal display, do not correspond to each other are empty fill each other

 

One consistent with many cases

# Create one of the authors table details
the Create the Table author (
  the above mentioned id int,
  name VARCHAR (64-),
  detail_id int
);
the Create the Table author_detail (
  the above mentioned id int,
  Phone VARCHAR (11)
);
# padding data
insert into author values (1 , 'Bob',. 1), (2, 'Tom', 2), (. 3, 'ruakei', 0);
INSERT INTO author_detail values (. 1, '13,344,556,677'), (2, '14,466,779,988'), (. 3 '12344332255');

# 内连
select author.id,name,phone from author join author_detail on author.detail_id = author_detail.id order by author.id;

# 全连
select author.id,name,phone from author left join author_detail on author.detail_id = author_detail.id
union
select author.id,name,phone from author right join author_detail on author.detail_id = author_detail.id
order by id;

 

Many to many: two table with two make the connection

# On a one to one basis, many relationships established relationship with the book's author

Before # Utilization of Table
Create Table author (
  ID int,
  name VARCHAR (64),
  detail_id int
);
INSERT INTO author values (. 1, 'Bob',. 1), (2, 'Tom', 2), (. 3, 'ruakei', 0);

Create a new book table #
Create Table Book (
  ID int,
  name VARCHAR (64),
  . Price decimal (5,2)
);
INSERT INTO Book values (. 1, 'Python', 3.66), (2, 'the Linux', 2.66 ), (3, 'Go' , 4.66);

# Create the author and the book's table of
the Create the Table author_book (
  the above mentioned id int,
  author_id int,
  book_id int
);
# Data: author-Book: 1-1,2 2-2,3 3-1,3
INSERT INTO author_book values (1 , 1,1), (2,1,2), (3,2,2), (4,2,3), (5,3,1), (6,3,3);

# The associated table eleven to establish a connection, so they need the query field
the SELECT book.name, book.price, author.name, author_detail.phone Book from
the Join author_book ON book.id = author_book.book_id
the Join author ON author_book. = author.id the author_id
left the Join author_detail ON author.detail_id = author_detail.id;

Guess you like

Origin www.cnblogs.com/wwei4332/p/11586715.html