Mysql研究之SQL语言的设计与编写完全解析 一、 SQL 语句分类 数据定义语言( DDL ): 用于定义和管理数据对象,包括数据库、数据表、视图、索引等。例如: CREATE 、 DROP 、 ALTER 等语句。 数据操作语言( DML ):【和表中的数据记录有关的语言】 用于操
Mysql研究之SQL语言的设计与编写完全解析一、SQL语句分类
数据定义语言(DDL):
用于定义和管理数据对象,包括数据库、数据表、视图、索引等。例如:CREATE、DROP、ALTER等语句。
数据操作语言(DML):【和表中的数据记录有关的语言】
用于操作数据库对象中所包含的数据。例如:INSERT、UPDATE、DELETE语句。
数据查询语言(DQL):
用于查询数据库对象中所包含的数据,能够进行单表查询、连接查询、嵌套查询,以及集合查询等各种复杂程度不同的数据库查询,并将数据返回到客户机中显示。例如:SELECT语句(占60%)。
数据控制语言(DCL):
是用来管理数据库的语言,包含管理权限及数据更改。例如:GRANT、REVOKE、COMMIT、ROLLBACK等语句。
二、SQL语句应用案例
1、DDL【可以按照以下格式写入一个文件,然后再粘贴到MySQL数据库中】
createtable if not exists cats (
idint not null auto_increment,
pidint not null default ’0′,
namevarchar(30) not null default ”,
desntext not null default ”,
primarykey(id),
indexname(name,pid)
);
createtable if not exists products(
idint not null auto_increment,
cidint not null default 0,
namevarchar(60) not null default ”,
pricedouble (7,2) not null default 0.00,
numint not null default 0,
desntext,
ptimeint not null default 0,
primarykey(id),
keypname(name,price)
);
2、DML
a)insert,插入表数据
insertinto 表名([字段列表])values(值列表),(值列表2),(值列表3),…,(值列表n);
特点:
1.如果在表名后没有给出字段列表,则值列表必须填充所有字段的值,必须按表中默认的顺序插入
2.所有需要写字段名的地方都不加单引号或双引号,但是建议所有值都要以字符形式使用
3.建议在插入数据时,最好给出字段列表,则值只要和字段列表一一对应即可,可以不按表中字段的顺序
?
b)update表名 set字段=’值‘[,字段2='值2',...,字段n='值n'][条件]#条件指定需要更改的记录
e.g. updatecats set pid=’3′ where id=’1′;
updatecats set pid=’99′ where id >= ’1′ && id
c)deletefrom 表名 [条件]
deletefrom cats; #清空数据表
truncatecats; #也可以清空数据表,效率更高,truncate将…截断
?
d)where条件
无论更新、删除、查找,只要写对条件就能准确找到要管理的一条或多条数据
【都可以使用各种运算符号,可以把字段当作一个变量来使用】
3、DQL【select】
SELECT[ALL | DISTINCT]
{*|table.*|[table.]field1[asalias1][,[table.]field2[as alias2]][.....]}
FROM 表名
[WHERE...]
[GROUPBY...]
[HAVING...]
[ORDERBY ...]
[LIMITcount]
使用SELECT查询语言,目的是可以按用户的想法将数据查出来,将结果返回!
SELECT[ALL | DISTINCT] #distinct 明显的,清楚的,有区别的
{*|table.*|[table.]field1[asalias1][,[table.]field2[as alias2]][.....]} #alias 别名,化名
FROM 表名
[WHERE...]
[GROUPBY...]
[HAVING...]
[ORDERBY ...]
[LIMITcount]
使用SELECT查询语言,目的是可以按用户的想法将数据查出来,将结果返回!
?
1、字段要列出要查询的字段
e.g. selectname,price from products;
selectprice,name from products;
select* from products;
selectproducts.* from products; #单表其实不需要使用表名
?
2、可以为每个字段起个别名【后面会用到(关键字,多表查询)】【表也可起别名(多表查询)】
e.g. selectname as bookname,price as bookprice from products;#使用别名;也可不加as;注意别名中有空格时,需要加单引号;
?
3、使用distinct作用与整个记录,取消重复的数据,只返回一个,而不是单独的一列
e.g. selectdistinct price ‘book price’ from products;
?
4、在SQL语句中使用表达式的列(可以使用算术运算符,条件运算符,逻辑运算符…)
游戏编程网www.cgzhw.com有详细的说明,这里就不再重复了。
5、WHERE可以在SELECT/UPDATE/DELETE中
a)可使用的逻辑运算符号(将多个条件组合)
&&/AND ||/OR !/NOT
b)可使用的比较运算符号
=#判断是否相等,与程序中的==作用相同
#判断是否相等,与=一致,但可以用于与NULL比较
!=/ #不等号
?
>
>=
c)程序中没有的运算符
ISNULL #与‘NULL’ 相等
ISNOT NULL
?
BETWEENAND
e.g. select* from products where id between 10 and 20;
与 “select* from products where id >= 10 && id 作用相同
?
NOTBETWEEN AND
?
IN
e.g. select* from products where id in(5,10,15,20);
updateproducts set num = 77 where id in(5,10,15,20);
deletefrom products where id in(5,10);
?
d)模糊查询
LIKE _(任意一个字符)和%(0个或多个任意字符)两个通配符号
e.g. select* from products where name like ‘______’; #查找任意名字为6个字符的数据
select* from products where name like ‘%java%’; #查询名字中包含有java的数据
?
NOTLIKE
e.g. select* from products where name not like ‘%java%’; #查询名字中不包含java字样的数据。
?
REGEXP/RLIKE【正则表达式】 #RegExp 正则表达式
e.g. select* from products where name regexp ‘^java’; #查找所有以java开头的数据
select* from products where name regexp ‘s$’; #查找所有以s结尾的数据
?
6、多表查询(连接查询),比较常用 #ambiguous
e.g. selectcats.name,products.name from cats,products;
selectc.name cname,c.desn cdesn,p.name pname,p.price,p.desn pdesn,p.numfrom carts c,products as p;#将A表中的记录与B表中的记录依次匹配,得到A*B种结果【笛卡尔乘积】,该结果是没有意义的。
selectc.name cname,c.desn cdesn,p.name pname,p.price,p.desn pdesn,p.numfrom carts c,products as p where c.id=p.cid;
selectc.name cname,c.desn cdesn,p.name pname,p.price,p.desn pdesn,p.numfrom carts c,products as p where c.id=p.cid and c.id=3;
selecta.id aid,a.name aname,b.id bid,b.name bname from cats a,catsb; #将单表分为多表,进行查询
selecta.id aid,a.name aname,b.id bid,b.name bname from cats a,cats b wherea.pid = b.id;
?
7、嵌套查询子查询
e.g. select* from products where cid in(select id from carts where name regexp’^j’) ;
select* from products where cid in(select id from carts where name like’j%’); #作用相同
?
8、orderby 字段 [asc正序]desc倒序
e.g. select* from order by name;
select* from order by price; #按价格非递减排序
select* from order by price desc; #非递增排序
select* from where cid > 5 order by price desc; #与where结合使用
?
9、limitcount【限制显示个数】
e.g. select* from limit 7;
select* from order by id desc limit 7;
select* from where id
select* from where id > 14 order by id asc limit 0,1; #limit0,1表示从第0个开始取,取1个
?
10、groupby 字段【分组】
常用函数:
count() #一个字段的总数
sum()
avg()#平均值
max()
min()
e.g. selectcount(*),sum(price),avg(price),max(price),min(price) from products;
selectcid,count(price),sum(price),avg(price),max(price),min (price) fromproducts group by cid;
selectcid,count(price),sum(price),avg(price),max(price),min (price) fromproducts group by cid having avg(price) > 50; #加having条件,与where类似
#having必须与gropby结合才能使用

MySQL 사용자를 추가하는 방법을 마스터하는 것은 데이터베이스 관리자 및 개발자가 데이터베이스의 보안 및 액세스 제어를 보장하기 때문에 데이터베이스 관리자 및 개발자에게 중요합니다. 1) CreateUser 명령을 사용하여 새 사용자를 만듭니다. 2) 보조금 명령을 통해 권한 할당, 3) FlushPrivileges를 사용하여 권한이 적용되도록하십시오.

ChooseCharfixed-lengthdata, varcharforvariable-lengthdata, andtextforlargetextfields.1) charisefficientsconsentent-lengthdatalikecodes.2) varcharsuitsvariable-lengthdatalikeNames, 밸런싱 플렉스 및 성능

MySQL에서 문자열 데이터 유형 및 인덱스를 처리하기위한 모범 사례는 다음과 같습니다. 1) 고정 길이의 Char, 가변 길이의 Varchar 및 큰 텍스트의 텍스트와 같은 적절한 문자열 유형 선택; 2) 인덱싱에 신중하고, 과도한 인덱싱을 피하고, 공통 쿼리에 대한 인덱스를 만듭니다. 3) 접두사 인덱스 및 전체 텍스트 인덱스를 사용하여 긴 문자열 검색을 최적화합니다. 4) 인덱스를 작고 효율적으로 유지하기 위해 인덱스를 정기적으로 모니터링하고 최적화합니다. 이러한 방법을 통해 읽기 및 쓰기 성능의 균형을 맞추고 데이터베이스 효율성을 향상시킬 수 있습니다.

Toaddauserremotelytomysql, 다음에 따르면 : 1) 1) ConnectTomysqlasRoot, 2) CreateEnewerwitHremoteAccess, 3) GrantNecessaryPrivileges 및 4) FlushPrivileges

tostorestringsefficiallyInmysql, choOseTherightDatAtypeBasedOnyOURNEDS : 1) USECHARFIXED-lengthstringsLikeCountryCodes.2) UseVarCharForVariable-lengthstringsLikenames.3) USETEXTFORLONG-FORMTEXTCONTENT.4) USETEXTFORLONG-FORMTEXTCONTENT.4) USETLOBFORBINARYIMAGES

MySQL의 블로브 및 텍스트 데이터 유형을 선택할 때 Blob은 이진 데이터를 저장하는 데 적합하며 텍스트는 텍스트 데이터를 저장하는 데 적합합니다. 1) Blob은 그림 및 오디오와 같은 이진 데이터에 적합합니다. 2) 텍스트는 기사 및 주석과 같은 텍스트 데이터에 적합합니다. 선택할 때는 데이터 속성 및 성능 최적화를 고려해야합니다.

mysqloffersvariouscharactersetsforstringdatatypes : 1) latin1forwesterneuropeanlanguages, 2) utf8formultulaultualsupport, 3) UTF8MB4F orextendedUnicodeincludeemojis, 4) UCS2Forfixed-widTheNcoding 및 5) asciiforbasiclatin.ChoingTherightSetensuresDatainTegrity

스트리밍 블로브는 메모리 사용량을 줄이고 성능을 향상시키기 때문에 직접 저장보다 더 좋습니다. 1) 파일을 점차적으로 읽고 처리함으로써 데이터베이스 팽창 및 성능 저하를 피합니다. 2) 스트리밍에는 더 복잡한 코드 로직이 필요하며 I/O 작업 수를 증가시킬 수 있습니다.


핫 AI 도구

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

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

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

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

인기 기사

뜨거운 도구

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경