[Database] database query operations

Query the database of
a constructed data
in order to facilitate the operation, first constructed the following data

  1. Student Table
create table `student` (
   `id` int unsigned primary key auto_increment,
   `name` char(32) not null unique,
   `sex` enum('男', '女') not null,
   `city` char(32) not null,
   `description` text,
   `birthday` date not null default '1995-1-1',
   `money` float(7, 2) default 0,
   `only_child` boolean
) charset=utf8;
insert into `student`
(`name`, `sex`, `city`, `description`, `birthday`,
`only_child`)
values
('郭德纲', '男', '北京', '班长', '1997/10/1', rand() * 100,
True),
('陈乔恩', '女', '上海', NULL, '1995/3/2', rand() * 100,
True),
('赵丽颖', '女', '北京', '班花, 不骄傲', '1995/4/4', rand()
* 100, False),
('王宝强', '男', '重庆', '超爱吃火锅', '1998/10/5', rand() *
100, False),
('赵雅芝', '女', '重庆', '全宇宙三好学生', '1996/7/9',
rand() * 100, True),
('张学友', '男', '上海', '奥林匹克总冠军!', '1993/5/2',
rand() * 100, False),
('陈意涵', '女', '上海', NULL, '1994/8/30', rand() * 100,
True),
('赵本山', '男', '南京', '副班长', '1995/6/1', rand() *
100, True),
('张柏芝', '女', '上海', NULL, '1997/2/28', rand() * 100,
False),
('吴亦凡', '男', '南京', '大碗宽面要不要?', '1995/6/1', 
rand() * 100, True),
('鹿晗', '男', '北京', NULL, '1993/5/28', rand() * 100,
True),
('关晓彤', '女', '北京', NULL, '1995/7/12', rand() * 100,
True),
('周杰伦', '男', '台北', '小伙人才啊', '1998/3/28', rand() *
100, False),
('马云', '男', '南京', '一个字:贼有钱', '1990/4/1', rand()
* 100, False),
('马化腾', '男', '上海', '马云死对头', '1990/11/28', rand()
* 100, False);
  1. Results table
create table score (
   `id` int unsigned primary key auto_increment,
   `math` float not null default 0,
   `english` float not null default 0
) charset=utf8;
insert into score (`math`, `english`)
values
(49, 71), (62, 66.7), (44, 86), (77.5, 74), (41, 75),
(82, 59.5), (64.5, 85), (62, 98), (44, 36), (67, 56),
(81, 90), (78, 70), (83, 66), (40, 90), (90, 90);

Second, the commonly used query

  1. SELECT: field expression
    SELECT query can do both, you can do output
    example:
select rand();  -- 随机数
select unix_timestamp(); -- 显示Unix时间戳
select id, name from student;
  1. FROM clause
    syntax: select field from table;
    FROM followed by data sources, data source you can write multiple data sources it is generally shows that may also be the result of other queries
SELECT student.name, score.math FROM student, score;
  1. WHERE clause: Filter by specified criteria
    syntax: select field from table where conditions;
    WHERE condition is to do a query, return only the result of the data True
    Example
select name from student where city = '上海';

Null value judgment: is null | is not null

select `name` from `student` where `description` is
null;
select `name` from `student` where `description` is not
null;

Range judgment:
the BETWEEN ... and ...
not ... and ... the BETWEEN

select id, math from score where math between 60 and 70;
select id, math from score where math not between 60 and
70;
select * from score where math>=80 and english<=60;  --
直接做比较判断
  1. GROUP BY: Query packets
    are grouped by a field, the field will return the same value as a group, the results of the query
    classification display for easy statistics.
    If there is to be placed behind WHERE WHERE is
    the syntax: select field from table group by group field;
select sex, count(id) from student group by sex;
-- 在group将需要的结果通过 “聚合函数” 拼接
select sex, group_concat(name) from student group by
sex;
-- 添加where语句
-- 按性别分组, 将上海地区的男生女生姓名连接起来
select sex, group_concat(name) from student where
city='上海' group by sex;
  1. HAVING
    HAVING and WHERE increase in SQL HAVING clause because, WHERE keyword
    can not be used with an aggregate function
    syntax: SELECT 字段 FROM 表名 HAVING 条件;
    WHERE: behind can not add an aggregate function can only be written after the data source.
    HAVING: Conditions must be in the field the result set, HAVING GROUP BY can be written in
    the back of the
    examples:
select `name`, `birthday` from `student` where
`birthday` > '1995-1-1';
select `name`, `birthday` from `student` having
`birthday` > '1995-1-1';
select `name` from `student` where `id` >= 5;
select `name` from `student` having `id` >= 5;  -- 错误
select * from student where id>=3 and city='北京';
select * from student having id>=3 and city='北京';
select * from student where id>=3 having city='北京';  --
混用
-- 取出每个城市中满足最小出生年份大于1995的
select city, group_concat(birthday) from student group
by city having min(birthday) > '1995-1-1';
  1. ORDER BY: Sort by field
    primary role is to sort ORDER BY
    ORDER BY written on the back GROUPBY, if there is also HAVING HAVING to write in after
    surface
    syntax: select field from table name order by sort field asc | desc;
    divided Ascending Descending asc desc, default asc (can not write)
    example
select * from student order by age;
select * from student order by age desc;
  1. LIMIT: limiting the number of extraction
select 字段 from 表名 limit m;  -- 从第 1 行到第 m 行
select 字段 from 表名 limit m, n;  -- 从第 m 行开始,往下取
n 行
select 字段 from 表名 limit m offset n;  -- 跳过前 n 行, 取
后面的 m 行
  1. DISTINCT: deduplication
    Example
select distinct city from student;
  1. dual table
    dual is a virtual table, just select ... from ... in order to ensure the integrity of statements
select now() from dual;

Third, the function
aggregate functions
Here Insert Picture DescriptionHere Insert Picture Description
numerical class function
Here Insert Picture Description

Date Calculation class function

Here Insert Picture Description

String related functions

Here Insert Picture Description
Other functions

Here Insert Picture Description
Fourth, multi-table queries
UNION joint inquiry
UNION operator for combining two or more SELECT statements result set.
union requirements:

  1. The number of fields on both sides of the select statement must be the same
  2. On both sides may have different types of data fields
  3. The default field names according to the left to set the table
  4. usage:
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;

INNER JOIN: the connector (intersection)

INNER JOIN keyword return line is present in at least one matching table.
grammar

SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
SELECT 字段
FROM1 INNER JOIN2
ON1.字段=2.字段;
-- 或:
SELECT column_name(s)
FROM table1 JOIN table2
ON table1.column_name=table2.column_name;

LEFT JOIN: LEFT JOIN

LEFT JOIN keyword from the left table (table1) returns all rows, even if the right table (table2)
does not match. If there is no match in the right table, the result to NULL.
grammar

SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name=table2.column_name;
-- 或:
SELECT column_name(s)
FROM table1
LEFT OUTER JOIN table2
ON table1.column_name=table2.column_name;

RIGHT JOIN: the right connection
RIGHT JOIN right keyword table (table2) returns all rows, even if the left table
(table1) does not match. If there is no match left table, the result is NULL.

grammar

SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name=table2.column_name;
-- 或:
SELECT column_name(s)
FROM table1
RIGHT OUTER JOIN table2
ON table1.column_name=table2.column_name;

FULL JOIN: fully connected
connection FULL JOIN is just left table (table1) and the right table (Table2) wherein a
table there is a match, then the return line. The equivalent of the LEFT JOIN and RIGHT JOIN the
result.
Special attention: MySQL does not support full join
grammar

SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;

NATURAL JOIN: NATURAL connecting
the connection 1.natural join NATURAL
2.natural left join connection to the natural left
3.natural right join right outer join natural
features:

1. determination condition can be automatically connected, based on the same name field
2. If there is no field of the same name, returns the Cartesian product
3 automatically returns results collated

  • Field only returns a connection
  • Connected on the front field
select * from stuinfo a natural join score b;
select * from stuinfo a natural left join score b;

CROSS JOIN: cross-connection

Features: returns a Cartesian Product

select * from a cross b;

using function

select * from stuinfo a left join score b on a.sid=b.sid; #主要作用,是自动查找关联字段,依据的是同名字段,但是同名字段是自己制定
select * from stuinfo a join score b using(sid);

Subqueries
query statement and a query

select name from student where id in (select id from score
where math > 10);

Fifth, view table

Features view of the table

  • A view is a specific subset of data, a virtual table, a list, or other data extracted from the formation of
    say a temporary table.
  • Creating a query table depends view.
  • View never go away unless you manually delete it.
  • Sometimes the view will help improve efficiency. Temporary tables do not help performance, resource consumption is
    who.
  • General view of the database is stored together with the temporary table in tempdb is always inside.
  • View suitable for use when connecting multiple browsing table; not suitable for add, delete, change, this can increase the execution
    line efficiency.
  • In the general view of the table name prefix v_ used to distinguish normal table.
  • The original table changes will affect the data view.

Create a view

Syntax: create view 视图名 as 查询语句
Example:


create view v_user_score as
select a.id, a.name, b.math, b.english
from student a inner join score b on a.id=b order by id;
-- 查询
select * from v_user_score;
-- 删除
drop view v_user_score;
Published 116 original articles · won praise 10 · views 1362

Guess you like

Origin blog.csdn.net/weixin_44727383/article/details/104955276