SQL第一节课

phpmyadmin

 

create table 表名
(
列名 数据类型 是否为空 (是否主键|是否唯一|外键关系),
列名 数据类型...(最后一列不加逗号)
)

create database 数据库名

insert into 数据库名.表名 values(数据,按列顺序填充逗号隔开)

update 表 set 列=新值 where 条件

delete from 表 where 条件

select 结果显示列 from 表 where 条件

C/S:Client Server
B/S:Brower Server

PHP主要实现B/S

.net IIS java TomCat

LAMP:Linux系统 A阿帕奇服务器 Mysql数据库 PHP语言

WAMP:Windows系统 A阿帕奇服务器 Mysql数据库 PHP语言

mysql:常用代码

create table ceshi1
(
Uid varchar(50) primary key,
Pwd varchar(50),
Name varchar(50)
Nation varchar(50),
foreign key (Nation) references Nation(Code)
)

写查询语句需要注意:

1.创建表的时候,最后一列后面不要写逗号

2.如果有多条语句一起执行,注意在语句之间加分号分隔

3.写代码所有符号都是半角的

关系型数据库:表和表之间是有关系存在的


创建表的几个关键字:

1.主键: primary key

2.非空: not null

3.自增长列:auto_increment

4.外键关系: foreign key (列名) references 表名(列名)

修改表:

1.alter table 表名 需要修改的内容

2.alter table 表名 add primary key (列名) #添加列为主键

3.alter table 表名 add primary key (列名,列名) #添加两个列为组合主键 add 添加 delete 删除

CRUD操作:

1.添加数据:
insert into 表名 values(值,'值') #要求values括号里面值的个数要跟表里面列数相同 字符串需要加''

insert into 表名 (列名,列名) values('值','值') #添加指定列的值

2.修改数据:
update 表名 set 列名=新值 where 条件

3.删除数据:
delete from 表名 where 条件

4.查询数据:

1.普通查询,查所有的:
select * from 表名 #查所有数据

select 列名,列名 from 表名 #查指定列

2.条件查询
select * from 表名 where 条件 #一个条件

select * from 表名 where 条件 and 条件 #两个条件并的关系

selecgt * from 表名 where 条件 or 条件 #两个条件或的关系

3.排序查询
select * from 表名 order by 列名 #默认升序排列 asc 如果要降序排列 desc

select * from 表名 order by 列名 desc,列名 asc #多列排序用逗号隔开

4.聚合函数
select count(列名) from 表名 #取个数

select sum(列名) from 表名 #查询列的和

select avg(列名) from 表名 #查询列的平均值

select max(列名) from 表名 #查询列的最大值

select min(列名) from 表名 #查询列的最小值

select * from 表名 where 列名 between 值 and 值 #列名的值 在两个值之间


5.分页查询
select * from 表名 limit (i-1)*n,m #跳过n条数据取m条数据 i页

6.分组查询
select 列名 from 表名 group by 列名 #简单分组查询

select 列名 from 表名 group by 列名 having count(*)>x #查询系列数量大于x的系列

7.去重查询
select distinct(列名) from 表名


8.修改列名
select 列名 as '新列名' from 表名

9.模糊查询
select * from 表名 where 列名 like'值%' # %代表任意多个字符 %值% 包含 _代表一个字符

10.离散查询
select * from 表名 where 列名 in('值','值','值')

select * from 表名 where 列名 not in('值','值','值')

Select * from 表名 where 列名<all (子查询多个数)

高级查询:

1.链接查询

select * from 表名,要连接的表名 #得出的结果称为笛卡尔积

select * from 表名,要连接的表名 where 表名.列名=要连接的表名.列名

join on 链接

select * from 表名 join 要连接的表名 #join链接

select * from 表名 join 要连接的表名 on 表名.列名=要连接的表名.列名

2.联合查询

select 列名,列名 from 表名
union
select 列名,列名 from 要联合的表名

列数要相同

3.子查询

1)无关子查询
select * from 表名 where 列名='要查询的内容'

select * from 表名 where 上面表的表名=(要查询的内容)

select * from 表名 where 关联的表名=(select * from 关联的表名 where 列名='要查询的内容')

子查询查询的结果被父查询使用,子查询可以单独执行的称为无关子查询

2)相关子查询


select * from 表名 where 列名<(内容的平均数) #查询内容小于括号内的平均数

select avg(列名) from 求平均的表名 where 列名='值' # 查询某列的平均值

select * from 表名 a where 列名<(select avg(列名) from 表名 b where b.列名='a.列名')

原文地址:https://www.cnblogs.com/xiongxiaobai/p/5426512.html