MySQL 데이터베이스의 기본 동작--DQL 동작

DQL - 기본 쿼리

개념

  • 데이터베이스 관리 시스템의 중요한 기능은 데이터 조회인데, 데이터 조회는 단순히 데이터베이스에 저장된 데이터를 반환하는 것이 아니라 데이터를 필터링하고 필요에 따라 데이터를 표시할 형식을 결정해야 합니다.
  • MySQL은 이러한 작업을 구현하기 위한 강력하고 유연한 명령문을 제공합니다.
  • MySQL 데이터베이스는 select 문을 사용하여 쿼리 작업을 구현합니다.

간소화된 구문

조건이 있는 테이블에서 열 이름을 선택합니다.

데이터 준비

create database if not exists mydb2;
use mydb2;
create table product(
pid int primary key auto_increment,
pname varchar(20) not null,
price double,
catagory_id varchar(20)
);

insert into product values(null,'海尔洗衣机',5000,'c001');
insert into product values(null,'美的冰箱',3000,'c001');
insert into product values(null,'格力空调',5000,'c001');
insert into product values(null,'九阳电饭煲',5000,'c001');

insert into product values(null,'啄木鸟衬衣',300,'c002');
insert into product values(null,'恒源祥西裤',800,'c002');
insert into product values(null,'花花公子夹克',440,'c002');
insert into product values(null,'劲爆休闲裤',266,'c002');
insert into product values(null,'海澜之家唯一',180,'c002');
insert into product values(null,'杰克琼斯运动裤',430,'c002');

insert into product values(null,'兰蔻面霜',300,'c003');
insert into product values(null,'雅诗兰黛精华水',200,'c003');
insert into product values(null,'香奈儿香水',350,'c003');
insert into product values(null,'SK-II神仙水',350,'c003');
insert into product values(null,'资生堂粉底液',180,'c003');

insert into product values(null,'老北京方便面',56,'c004');
insert into product values(null,'良品铺子海带丝',17,'c004');
insert into product values(null,'三只松鼠坚果',88,'c004');

간단한 쿼리

-- --简单查询
-- --1查询所有商品

select  pid,pname ,price,catagory_id from product;
-- 或者select * from product
-- 

-- 2查询商品名和商品价格
select pname,price from product;

-- 3.1 表别名
select * from product as p;
-- 或者select * from product p;
-- select p.id,u.id from product,user;
-- 3.2 列别名
select pname as '商品名',price '商品价格' from product;
-- 4去掉重复值
select distinct price from product;
-- 或者select distinct * from product;
-- 5查询结果是表达式(运算查询):将所有商品加价十元后显示
select pname,price+10 new_price from product;

운영자

  • 소개

데이터베이스의 테이블 구조가 결정된 후 테이블의 데이터가 나타내는 의미가 결정되었습니다. MySQL 연산자와 함께 작동하여 테이블 구조 이외의 데이터로 돌아갈 수 있습니다.

예를 들어 학생 테이블에 학생의 출생 연도를 나타내는 출생 필드가 있고, 현재 시간에서 이 필드를 빼면 학생의 실제 나이 데이터를 얻을 수 있습니다.

MySQL은 4개의 연산자를 지원합니다.

  • 산술 연산자
  • 비교 연산자
  • 논리 연산자
  • 비트 연산자

 산술 연산자

+ 덧셈
- 빼기
* 곱셈
/ 또는 DIV 나누기 연산, 몫 반환
% 또는 MOD 나머지 연산, 나머지 반환
산술 연산자 설명하다

비교 연산자

 논리 연산자

 비트 연산자

기본 쿼리

-- 查询商品名称为海尔洗衣机的所有商品
 select * from product where pname='海尔洗衣机';
 -- 查询价格为800商品
 select * from product where price=800;
-- 查询价格不是800的所有商品
select * from product where price!=800;
select * from product where price<>800;
select * from product where not (price=800);
-- 查询商品价格大于60元的所有商品信息
select * from product where price>60;
-- 查询商品价格在200到1000之间所有商品
select * from product where price >= 200 and price <= 1000;
select * from product where price >= 200 and price <=1000;

select * from product where price between 200 and 1000;
-- 查询商品价格是200或800的所有商品
select * from product where price=200 or price=800;
select * from product where price in (200,800);
-- 查询含有‘裤'字的所有商品
select * from product where pname like '%裤%';
-- 查询以'海'开头的所有商品
select * from product where pname like '海%';-- 百分号表示任意字符
-- 查询第二个字为'蔻'的所有商品
select * from product where pname like '_蔻%';
-- 查询category_id为null的商品
select * from product where catagory_id is null;
-- 查询category_id不为null分类的商品
select * from product where catagory_id is not null;
-- 使用least求最小值
select least (10,5,20) as small_number;
select least (10,null,20) as small_number;-- 如果求最小、大值时有null,则无法比较,结果之间为null
-- 使用greatest求最大值

 select greatest (10,5,20) as max_number;

연산자 연산 - 산술 연산자

-- 1算数运算符
select 6 + 2;
select 6 - 2;
select 6 / 2;
select 6 % 2;

-- 将所有商品加10 元
select pname,price+10 as new_price from product;
-- 将所有商品上调10%
select pname,price * 1.1 as new_price from product;

 비트 연산자(이해)

쿼리 정렬

  • 소개하다

읽은 데이터를 정렬하려는 경우 MySQL의 order by 절을 사용하여 정렬할 필드를 설정한 다음 검색 결과를 반환할 수 있습니다.

select
字段名1,字段名2,...
from 表名
order by 字段名1 [asc|desc],字段名2[asc|desc]
  • 특징

1.asc는 오름차순, desc는 내림차순을 의미합니다 . 쓰지 않으면 기본 오름차순입니다.

2. 단일 필드, 다중 필드, 표현식, 함수, 별칭을 지원하기 위해 절에서 순서가 사용됩니다.

3. order by 절은 쿼리 문의 끝에 위치합니다. LIMIT 절을 제외하고. 

작동하다

-- 1.使用价格排序(降序)
select * from product order by price desc;
-- 2.在价格排序(降序)的基础上,以分类排序(降序)
select * from product order by price desc,category_id asc;
-- 3.显示商品的价格(去重复),并排序(降序)
select distinct price from product order by price desc;

집계 쿼리

소개

기존에 했던 쿼리는 모두 조건에 따라 한 줄씩 판단하는 수평 쿼리인 반면 집계 함수를 사용한 쿼리는 컬럼의 값을 계산하여 하나의 값을 반환하는 수직 쿼리이다. , 집계 함수 Null 값은 무시됩니다.

작동하다

-- 1 查询商品的总条数
select count(*) from product;
-- 2 查询价格大于200商品的总条数
select count(*) from product where price > 200;
-- 3 查询分类为'c001'的所有商品的总和
select sum(price) from product where category_id = 'c001';
-- 4 查询商品的最大价格
select max(price) from product;
-- 5 查询商品的最小价格
select min(price) from product;
-- 6 查询分类为'c002'所有商品的平均价格
select avg(price) from product where category_id = 'c002';

 NULL 값의 집계 쿼리 처리

1. count 함수는 null 값을 처리합니다.

카운트 함수의 매개변수가 별표( * ) 이면 모든 레코드의 수를 카운트합니다. 그리고 매개변수가 특정 필드인 경우 null 값을 포함하는 레코드의 수는 계산되지 않습니다.

2. sum avg 함수는 null 값을 처리합니다 .

이 두 함수는 레코드가 존재하지 않는 것처럼 null 값의 존재를 무시합니다. 평균을 계산할 때 숫자를 세지 않고 생성할 때 default=0으로 가정하면 괜찮습니다.

3. max min 함수는 null 값을 처리합니다 .

 max min 함수는 null 값의 존재 도 무시합니다 .

작동하다

-- 创建表
create table test_null( 
 c1 varchar(20), 
 c2 int 
);

-- 插入数据
insert into test_null values('aaa',3);
insert into test_null values('bbb',3);
insert into test_null values('ccc',null);
insert into test_null values('ddd',6);
 
-- 测试
select count(*), count(1), count(c2) from test_null;
select sum(c2),max(c2),min(c2),avg(c2) from test_null;

그룹 쿼리(매우 중요)

그룹 쿼리는 쿼리 정보를 그룹화하기 위해 group by 절을 사용하는 것을 말합니다.

체재

그룹 조건이 있는 그룹 필드별로 테이블 이름 그룹에서 필드 1, 필드 2...를 선택합니다.

-- 分组查询
-- select 字段1,字段2...from 表名 group by 分组字段 having 分组条件;
-- 统计各个分类商品的个数,分组之后select后面只能写分组字段和聚合函数
select catagory_id,count(*) from product group by catagory_id;

그룹화 후 조건부 필터링 -having

그룹화 후 통계 결과를 필터링하려면 where 대신에 having을 사용해야 합니다.
where 절은 FROM 절 에 지정된 작업에 의해 생성된 행을 필터링하는 데 사용됩니다.
group by  절은 WHERE 절의 출력을 그룹화하는 데 사용됩니다 .
having 절은 그룹화된 결과에서 행을 필터링하는 데 사용됩니다.
체재

그룹 조건이 있는 그룹 필드별로 테이블 이름 그룹에서 필드 1, 필드 2...를 선택합니다.

작동하다

-- 2.统计各个分类商品的个数,且只显示个数大于4的信息
select category_id ,count(*) from product group by category_id having count(*) > 4;
顺序(from, where, group by, have)

페이지 매김 쿼리 제한

소개

페이징 쿼리는 프로젝트 개발에서 흔히 볼 수 있으며, 데이터 양이 많고 디스플레이 화면의 길이가 제한되어 있기 때문에 데이터를 페이지 단위로 표시해야 합니다. 예를 들어, 30개의 데이터 항목이 있고, 각 페이지에 5개의 항목이 표시되고, 첫 번째 페이지에 1~5개의 항목이 표시되고, 두 번째 페이지에 6~10개의 항목이 표시됩니다. 

체재

-- 방법 1 - 처음 n개 항목 표시

선택 필드 1, 필드 2...에서 제한 n을 나타냅니다.

-- 모드 2-페이징 표시

선택 필드 1, 필드 2...에서 제한 m,n을 나타냅니다.

m: 시작할 인덱스를 나타내는 정수, 계산 방법(현재 페이지 - 1) * 각 페이지에 표시되는 항목 수

n: 쿼리할 데이터 조각 수를 나타내는 정수

작동하다

-- 查询product表的前5条记录 
select * from product limit 5 

-- 从第4条开始显示,显示5条 
select * from product limit 3,5
INSERT INTO SELECT 문
체재

Table2(field1,field2,…)에 삽입 Table1에서 value1,value2,… 선택 或者:

Table2에 삽입 table1에서 * 선택

SELECT INTO FROM 문

소개

한 테이블에서 다른 테이블로 데이터를 가져오려면 SELECT INTO INSERT INTO SELECT의 두 가지 옵션이 있습니다.

체재

SELECT vale1, value2를 Table1에서 Table2로

삽입 시 자동으로 Table2 테이블이 생성되고 Table1의 지정된 필드 데이터가 Table2에 복사되기 때문에 대상 테이블 Table2가 존재하지 않는 것이 필요하다.

부록 전체 코드

create database if not exists mydb2;
use mydb2;
create table product(
pid int primary key auto_increment,
pname varchar(20) not null,
price double,
catagory_id varchar(20)
);

insert into product values(null,'海尔洗衣机',5000,'c001');
insert into product values(null,'美的冰箱',3000,'c001');
insert into product values(null,'格力空调',5000,'c001');
insert into product values(null,'九阳电饭煲',5000,'c001');

insert into product values(null,'啄木鸟衬衣',300,'c002');
insert into product values(null,'恒源祥西裤',800,'c002');
insert into product values(null,'花花公子夹克',440,'c002');
insert into product values(null,'劲爆休闲裤',266,'c002');
insert into product values(null,'海澜之家唯一',180,'c002');
insert into product values(null,'杰克琼斯运动裤',430,'c002');

insert into product values(null,'兰蔻面霜',300,'c003');
insert into product values(null,'雅诗兰黛精华水',200,'c003');
insert into product values(null,'香奈儿香水',350,'c003');
insert into product values(null,'SK-II神仙水',350,'c003');
insert into product values(null,'资生堂粉底液',180,'c003');

insert into product values(null,'老北京方便面',56,'c004');
insert into product values(null,'良品铺子海带丝',17,'c004');
insert into product values(null,'三只松鼠坚果',88,null);

-- --简单查询
-- --1查询所有商品

select  pid,pname ,price,catagory_id from product;
-- 或者select * from product
-- 

-- 2查询商品名和商品价格
select pname,price from product;

-- 3.1 表别名
select * from product as p;
-- 或者select * from product p;
-- select p.id,u.id from product,user;
-- 3.2 列别名
select pname as '商品名',price '商品价格' from product;
-- 4去掉重复值
select distinct price from product;
-- 或者select distinct * from product;
-- 5查询结果是表达式(运算查询):将所有商品加价十元后显示
select pname,price+10 new_price from product;

-- 运算符
use mydb2;
-- 1算数运算符
select 6 + 2;
select 6 - 2;
select 6 / 2;
select 6 % 2;

-- 将所有商品加10 元
select pname,price+10 as new_price from product;
-- 将所有商品上调10%
select pname,price * 1.1 as new_price from product;
-- 2 比较运算符合
 
 -- 3 逻辑运算符
 -- 查询商品名称为海尔洗衣机的所有商品
 select * from product where pname='海尔洗衣机';
 -- 查询价格为800商品
 select * from product where price=800;
-- 查询价格不是800的所有商品
select * from product where price!=800;
select * from product where price<>800;
select * from product where not (price=800);
-- 查询商品价格大于60元的所有商品信息
select * from product where price>60;
-- 查询商品价格在200到1000之间所有商品
select * from product where price >= 200 and price <= 1000;
select * from product where price >= 200 and price <=1000;

select * from product where price between 200 and 1000;
-- 查询商品价格是200或800的所有商品
select * from product where price=200 or price=800;
select * from product where price in (200,800);
-- 查询含有‘裤'字的所有商品
select * from product where pname like '%裤%';
-- 查询以'海'开头的所有商品
select * from product where pname like '海%';-- 百分号表示任意字符
-- 查询第二个字为'蔻'的所有商品
select * from product where pname like '_蔻%';
-- 查询category_id为null的商品
select * from product where catagory_id is null;
-- 查询category_id不为null分类的商品
select * from product where catagory_id is not null;
-- 使用least求最小值
select least (10,5,20) as small_number;
select least (10,null,20) as small_number;-- 如果求最小、大值时有null,则无法比较,结果之间为null
-- 使用greatest求最大值

 select greatest (10,5,20) as max_number;
 -- 4位运算符
-- 使用价格排序(降序)

select * from product order by price desc;
-- 2在价格降序的基础上,以分类降序
select * from product order by price desc,catagory_id desc;
-- 3.显示商品的价格(去重复),并排序(降序)
select distinct price from product order by price desc;

-- 聚合查询

-- 1 查询商品的总条数
select count(pid) from product;
select count(*) from product;
-- 2 查询价格大于200商品的总条数
select count(pid) from product where price > 200;
-- 3 查询分类为'c001'的所有商品的总和
select 
-- 4 查询商品的最大价格
select sum(price) from product where price > 200;
-- 5 查询商品的最小价格
select max(price) from product;
select max(price) max_price, min(price) min_price from product;
-- 6 查询分类为'c002'所有商品的平均价格

select avg(price) from product where catagory_id ='c002';



-- 分组查询
-- select 字段1,字段2...from 表名 group by 分组字段 having 分组条件;
-- 统计各个分类商品的个数,分组之后select后面只能写分组字段和聚合函数
select catagory_id,count(*) from product group by catagory_id;


-- 分页查询
-- 1.查询product表的前五条记录
select * from product limit 5;
-- 2从第四天开始显示,显示五条
 select * from product limit 3,5;-- 从第四天开始显示,显示五条

추천

출처blog.csdn.net/weixin_44734502/article/details/126267780