찾다
데이터 베이스MySQL 튜토리얼day12 mysql复杂sql语句编纂

day12 mysql复杂sql语句编写 SQL基本部分: 1、数据库操作相关SQL ---- database 创建数据库 create database 数据库名称; ------ 在sql后通过 character set 指定数据库本身字符集,如果没有指定将服务器默认 * 服务器默认字符集 mysql安装目录/my.ini [mysq

day12 mysql复杂sql语句编写

SQL基本部分:
1、数据库操作相关SQL ---- database
创建数据库 create database 数据库名称; ------ 在sql后通过 character set 指定数据库本身字符集,如果没有指定将服务器默认
* 服务器默认字符集 mysql安装目录/my.ini [mysqld] default-character-set

查看当前有哪些数据库 show databases;

修改数据库(修改数据库字符集) 数据库字符集存放mysql安装目录/data/数据库文件夹/db.opt
alter database 数据库名称 character set 字符集;
* collate 校对方式 ----- 用于数据库排序; 每一种字符集都存在一种默认校对方式(可以不用修改)

删除数据库 drop database 数据库名称;

切换数据库(设置当前使用数据库) use 数据库名称;
* select database(); 查看当前使用数据库

2、数据表操作相关SQL ---- table表结构
创建数据表 create table 表名(列名 类型(长度) 约束,列名 类型(长度) 约束... ) ----- 在创建表之前必须指定数据库
* 查看当前有哪些数据表 show tables;

查看数据表表结构 desc table;

修改表结构:
修改列类型(长度) : alter table 表名 modify ...
添加一个新列 : alter table 表名 add ...
修改列名称 : alter table 表名 change ...
删除列 : alter table 表名 drop 列名
修改表名 : rename table 旧表名 to 新表名

* table 在创建时 character set 指定表字符集,如果没有指定采用数据库默认字符集

删除表 drop table 表名;

3、数据记录增删改查? insert update delete select
数据记录插入 insert into 表名(列,...)? values(值,...);
* 值的顺序和列顺序一致,个数一致 , 在开发中经常省略列名,值按照表结构所有字段进行设值

数据查看 select * from 表名;

数据记录修改 update 表名 set 列名=值,列名= 值 where 条件语句

数据记录删除 delete from 表名 where 语句
* truncate 与 delete区别 ? truncate删除表,重新创建, delete from 逐行删除----- 性能truncate好于 delete,delete被事务控制,删除后回滚取消删除,truncate不可恢复


select 语句
S - F - W - G - H - O
select ... from ... where ... group by ... having ... order by ... ; 顺序固定的

1、from 指定查询数据表
2、where 前置过滤条件 --- 将表数据过滤掉一部分
3、group by 对where 过滤后数据进行分组
4、having 对分组后结果添加条件过滤
5、select 指定检索哪些字段
6、order by 对检索结果排序

4、数据库备份和恢复
备份命令: mysqldump -u 用户名 -p 数据库名 > sql脚本位置 (回车输入密码)
恢复命令: mysql -u 用户名 -p 数据库名 * 在mysql连接后,通过source 进行数据库恢复 source sql脚本位置

5、数据库完整性约束 ----- 保证数据表中记录完整性
主键约束 primary key : 用来指定数据表数据记录的唯一标识
唯一约束 unique : 该字段取值唯一
非空约束 not null ; 该字段值不能为null
外键约束 foreign key : 当两个数据表存在关联时,添加外键约束,外键约束引用另一张表主键
条件约束 check : mysql不支持 Oracle支持 check age* 完整性约束有5类

----------------------------------------------------------
多表设计
数据表与数据表之间关系三种:实体之间关系 多对多、一对多、一对一

多对多案例:项目和程序员
一个项目可以由多个程序员参与
一个程序员可以参与多个项目开发

建表原则:多对多关系,必须引入第三张数据表,同时引入另两张实体表主键作为外键

一对多案例:老师与课程
一个老师可以教授多门课程
一门课程只能有一个老师教授

建表原则:一对多关系,在多的一方添加一方 主键作为外键

一对一关系:班级与班长关系
一个班只能有一个班长
一个班长只能负责一个班

* 该关系比较少见
建表原则:一对一关系,可以在任何一方添加 另一方主键作为外键

建表练习:
设计学生成绩管理系统数据表
1、每个教师可以教多门课程
2、每门课程可以由多个学生选修
3、每个学生可以选修多门课程
4、学生选修课程要有成绩

关系表表名,通常用两个实体表表名组合而成!

-------------------------------------------------------------------------------
笛卡尔积
当两个数据表进行关联查询时,用第一张数据表每一条记录去匹配第二张数据表每一条记录。

第一张表10条数据
第二张表20条数据
使用笛卡尔积 结果 10*20 = 200 条记录

在实际开发中,获得笛卡尔积中有意义的记录 ? ---- 连接查询
内连接
外连接

内连接 : 将两张表相同意义字段连接起来
select * from A,B where A.A_ID = B.A_ID; 条件 A表中A_ID与 B表中 A_ID 相等匹配
* 返回结果一定是两个表都存在信息 , 最有意义的信息,如果第一张表记录在第二张表找不到匹配信息,不显示,第二张表记录在第一张表无匹配信息,不显示

第一张表10条数据
第二张表20条数据
内连接 结果

语法:select * from a inner join b on A.A_ID = B.A_ID;
简化:select * from a,b where A.A_ID = B.A_ID;

外连接:左外连接、右外连接、全外连接
左外连接 :用第一张表每条记录去匹配第二张表对应记录,无论是否找到匹配信息,都显示第一张表匹配结果
例如:每个水果价格 ? 没有价格水果也要显示
select * from a left outer join b on A.A_ID = B.A_ID ;

第一张表10条数据
第二张表20条数据
左外连接 --- 10条

右外连接:从第二张表找第一张表匹配记录,无论是否找到,第二张表所有记录都显示
select * from a right outer join b on A.A_ID = B.A_ID ;


第一张表10条数据
第二张表20条数据
右外连接 --- 20条

全外连接:左外连接与右外连接 结果和 ---- 排除重复数据
select * from a full outer join b on A.A_ID = B.A_ID ; ----- MySQL 不支持

使用union关键字实现全外连接效果
select * from A left outer join B on A.A_ID = B.A_ID
union
select * from A right outer join B on A.A_ID = B.A_ID;

------------------------------------------------------------------------------------
关联子查询:将第一个查询结果 ,作为第二个查询条件
查询student表中年龄最大学员的信息
select * from student where age = (select max(age) from student);

等价于
select max(age) from student; ----- 25
select * from student where age = 25; ----- 学生信息

IN/EXISTS 当前查询记录在子查询结果中存在
查询所有成绩小于60分的同学名称

查询studentcource表成绩小于60 所有记录
select student_id from studentcource where score 再根据id去查询学生表,得知学生姓名
select * from student where id in(2,8);

select * from student where id in(select student_id from studentcource where score

exists实现上面in 语句效果
select name from student where exists (select * from studentcource where score

select * from studentcource,student where score

select name from student where exists (select * from studentcource where score

* 在实际开发中 exists比 in效率要高

ANY、SOME、ALL 用法
SOME和ANY作用相同的? ----- 一些 >any(1,2,3) 大于任何一个都可以 等价于 >min
ALL ---- 所有? >all(1,2,3) 必须同时大于三个值?? 等价于 >max

查询获得最高分的学生学号
select max(score) from studentcource; 最高学分
select student_id from studentcource where score = (select max(score) from studentcource);
* 自我比较
select student_id from studentcource where score >=all(select score from studentcource);

查询编号2课程比编号1课程成绩高所有学号
select score from studentcource where cource_id = 2 and score > any(select score from studentcource where cource_id = 1);

select score from studentcource where cource_id = 2; 课程2所有成绩
select score from studentcource where cource_id = 1; 课程1所有成绩

使用union将两个查询结果合并,union 排重重复数据 union all 不会排重重复数据
* 合并时列名必须一致

------------------------------------------------------------------------------------------------------
查询语文课程比数学课程成绩高的所有学生的学号
mysql> select * from cource,studentcource where cource.id = studentcource.cource
_id and cource.name='语文';
+----+------+------------+------------+-----------+-------+
| id | name | teacher_id | student_id | cource_id | score |
+----+------+------------+------------+-----------+-------+
|? 1 | 语文 |????????? 1 |????????? 1 |???????? 1 |??? 80 |
|? 1 | 语文 |????????? 1 |????????? 3 |???????? 1 |??? 71 |
|? 1 | 语文 |????????? 1 |????????? 5 |???????? 1 |??? 60 |
|? 1 | 语文 |????????? 1 |????????? 6 |???????? 1 |??? 76 |
|? 1 | 语文 |????????? 1 |???????? 10 |???????? 1 |??? 77 |
+----+------+------------+------------+-----------+-------+
5 rows in set (0.02 sec)

mysql> select * from cource,studentcource where cource.id = studentcource.cource
_id and cource.name='数学';
+----+------+------------+------------+-----------+-------+
| id | name | teacher_id | student_id | cource_id | score |
+----+------+------------+------------+-----------+-------+
|? 2 | 数学 |????????? 1 |????????? 1 |???????? 2 |??? 90 |
|? 2 | 数学 |????????? 1 |????????? 2 |???????? 2 |??? 53 |
|? 2 | 数学 |????????? 1 |????????? 3 |???????? 2 |??? 70 |
|? 2 | 数学 |????????? 1 |????????? 4 |???????? 2 |??? 90 |
|? 2 | 数学 |????????? 1 |????????? 5 |???????? 2 |??? 70 |
|? 2 | 数学 |????????? 1 |????????? 6 |???????? 2 |??? 88 |
|? 2 | 数学 |????????? 1 |????????? 8 |???????? 2 |??? 71 |
|? 2 | 数学 |????????? 1 |????????? 9 |???????? 2 |??? 88 |
|? 2 | 数学 |????????? 1 |???????? 10 |???????? 2 |??? 76 |
+----+------+------------+------------+-----------+-------+
9 rows in set (0.00 sec)

select t1.student_id,t1.score 语文,t2.score 数学 from (select * from cource,studentcource where cource.id = studentcource.cource_id and cource.name='语文') t1,(select * from cource,studentcource where cource.id = studentcource.cource_id and cource.name='数学') t2 where t1.student_id = t2.student_id and t1.score > t2.score;

查询平均成绩大于70分的同学的学号和平均成绩
* 按人取平均成绩 ------ 分组
select student_id,avg(score) from studentcource group by student_id having avg(score)>70;
* 打印学生姓名
select student.name,t.avgscore from student,(select student_id,avg(score) avgscore from studentcource group by student_id having avg(score)>70) t where student.id = t.student_id;

查询所有同学的学号、姓名、选课数、总成绩
*学生信息:select * from student;
*选课数、总成绩 select student_id,count(*),sum(score) from studentcource group by student_id;

select student.id 学号,student.name 姓名,t.courcenum 选课数, t.sumscore 总成绩 from student,(select student_id,count(*) courcenum,sum(score) sumscore from studentcource group by student_id) t where student.id = t.student_id;?

查询没学过关羽老师课的同学的学号、姓名
* 关羽老师教什么课 select cource.id from teacher,cource where teacher.id = cource.teacher_id and teacher.name='关羽';
* 选过关羽老师课 select distinct student_id from studentcource where cource_id in (select cource.id from teacher,cource where teacher.id = cource.teacher_id and teacher.name='关羽');

select id,name from student where id not in (select distinct student_id from studentcource where cource_id in (select cource.id from teacher,cource where teacher.id = cource.teacher_id and teacher.name='关羽'));

查询学过语文并且也学过数学课程的同学的学号、姓名
* 语文和数据 课程编号? select id from cource where name='语文' or name='数学';
* 学过语文的学生 select * from cource,studentcource where cource.id = studentcource.cource_id and cource.name='语文';
* 学过数学的学生 select * from cource,studentcource where cource.id = studentcource.cource_id and cource.name='数学';

select t1.student_id? from (select * from cource,studentcource where cource.id = studentcource.cource_id and cource.name='语文') t1, (select * from cource,studentcource where cource.id = studentcource.cource_id and cource.name='数学') t2 where t1.student_id = t2.student_id ;

select student.id,student.name from student,(select t1.student_id? from (select * from cource,studentcource where cource.id = studentcource.cource_id and cource.name='语文') t1, (select * from cource,studentcource where cource.id = studentcource.cource_id and cource.name='数学') t2 where t1.student_id = t2.student_id) t where student.id = t.student_id;

查询学过赵云老师所教的所有课的同学的学号、姓名

查询没有学三门课以上的同学的学号、姓名

查询至少有一门课与学号为“1”的同学所学相同的同学的学号和姓名

查询和小李同学学习的课程完全相同的其他同学学号和姓名

查询各科成绩最高和最低的分

查询学生信息和平均成绩

查询上海和北京学生数量

查询不及格的学生信息和课程信息

查询每门功成绩最好的前两名

统计每门课程的学生选修人数(超过两人的进行统计)

把成绩表中“关羽”老师教的课的成绩都更改为此课程的平均成绩

?

?

?

?

?

?

?

?

?

?

?

?

?

?

?

?

?

?

?

?

?

?

?

?

?

?


?

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
MySQL Blob : 한계가 있습니까?MySQL Blob : 한계가 있습니까?May 08, 2025 am 12:22 AM

mysqlblobshavelimits : tinyblob (255bodes), blob (65,535 bytes), mediumblob (16,777,215 bctes), andlongblob (4,294,967,295 Bytes) .tousebl obseffectical : 1) 고려 사항을 고려합니다

MySQL : 사용자 생성을 자동화하는 가장 좋은 도구는 무엇입니까?MySQL : 사용자 생성을 자동화하는 가장 좋은 도구는 무엇입니까?May 08, 2025 am 12:22 AM

MySQL에서 사용자 생성을 자동화하기위한 최고의 도구 및 기술은 다음과 같습니다. 1. MySQLworkBench, 중소형 환경에 적합하고 사용하기 쉽지만 자원 소비가 높습니다. 2. 다중 서버 환경에 적합한 Ansible, 간단하지만 가파른 학습 곡선; 3. 사용자 정의 파이썬 스크립트, 유연하지만 스크립트 보안을 보장해야합니다. 4. 꼭두각시와 요리사는 대규모 환경에 적합하며 복잡하지만 확장 가능합니다. 선택할 때 척도, 학습 곡선 및 통합 요구를 고려해야합니다.

MySQL : 블로브 내부를 검색 할 수 있습니까?MySQL : 블로브 내부를 검색 할 수 있습니까?May 08, 2025 am 12:20 AM

예, youcansearchinsideablobinmysqlusingspecifictechniques.1) converttheblobtoautf-8stringwithConvertFunctionandSearchusing

MySQL 문자열 데이터 유형 : 포괄적 인 가이드MySQL 문자열 데이터 유형 : 포괄적 인 가이드May 08, 2025 am 12:14 AM

mysqloffersvariousStringDatatatypes : 1) charfixed-lengthstrings, 이상적인 원인이 길이의 길이가 길이 스트링스, 적합한 포르 플리드 슬리 키나 이름; 3) TextTypesforlargerText, goodforblogpostsbutcactperformance;

MySQL Blobs 마스터 링 : 단계별 자습서MySQL Blobs 마스터 링 : 단계별 자습서May 08, 2025 am 12:01 AM

TomasterMySQLBLOBs,followthesesteps:1)ChoosetheappropriateBLOBtype(TINYBLOB,BLOB,MEDIUMBLOB,LONGBLOB)basedondatasize.2)InsertdatausingLOAD_FILEforefficiency.3)Storefilereferencesinsteadoffilestoimproveperformance.4)UseDUMPFILEtoretrieveandsaveBLOBsco

MySQL의 Blob Data Type : 개발자를위한 상세한 개요MySQL의 Blob Data Type : 개발자를위한 상세한 개요May 07, 2025 pm 05:41 PM

blobdatatypesinmysqlareusedforvoringlargebinarydatalikeimagesoraudio.1) useblobtypes (tinyblobtolongblob) 기반 론다 타지 세인. 2) StoreBlobsin perplate petooptimize 성능.

명령 줄에서 MySQL에 사용자를 추가하는 방법명령 줄에서 MySQL에 사용자를 추가하는 방법May 07, 2025 pm 05:01 PM

toadduserstomysqlfromthecommandline, loginasroot, whenUseCreateUser'Username '@'host'IdentifiedBy'Password '; toCreateAwUser.grantPerMissionswithGrantAllilegesOndatabase

MySQL의 다른 문자열 데이터 유형은 무엇입니까? 자세한 개요MySQL의 다른 문자열 데이터 유형은 무엇입니까? 자세한 개요May 07, 2025 pm 03:33 PM

mysqlofferSeightStringDatatatypes : char, varchar, binary, varbinary, blob, text, enum and set.1) charisfix-length, 2) varcharisvariable-length, 효율적 인 datalikenames.3) binaryandvarbinary-binary Binary Binary Binary Binary Binary Binary Binary-Binary

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

안전한 시험 브라우저

안전한 시험 브라우저

안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!