SQL语句

1.sql基础
创建数据库:
CREATE DATEBASE IF NOT EXISTS user

删除数据库
DROP DATEBASE IF EXISTS user

创建新表
create table user(col1 type1 [not null] [primary key],col2 type2 [not null],…)

删除新表
DROP TABLE user

增加一个列
Alter table user add column col type

添加主键
Alter table user add primary key(id)

删除主键
Alter table user drop primary key(id)

创建索引
create [unique] index idxname on user(col….)

删除索引
drop index idxname

创建视图
create view viewname as select statement

查询语句
select * from user where id=?
select name,age where id=?

插入语句
insert into user (name,age,address)values(?,?,?)

删除
delete from user where id=?

更新
update user set name=?where id=?

排序
select * from user order by name desc

总数
select count as totalcount from user

求和
select sum(field1) as sumvalue from user

平均
select avg(field1) as avgvalue from user

最大
select max(field1) as maxvalue from user

最小
select min(field1) as minvalue from user

UNION 运算符
UNION 运算符通过组合其他两个结果表(例如 TABLE1 和 TABLE2)并消去表中任何重复行而派生出一个结果表。当 ALL 随 UNION一起使用时(即 UNION ALL),不消除重复行。两种情况下,派生表的每一行不是来自 TABLE1 就是来自 TABLE2。

EXCEPT 运算符
EXCEPT 运算符通过包括所有在 TABLE1 中但不在 TABLE2 中的行并消除所有重复行而派生出一个结果表。当 ALL 随 EXCEPT 一起使用时 (EXCEPT ALL),不消除重复行。

INTERSECT 运算符
INTERSECT 运算符通过只包括 TABLE1 和 TABLE2 中都有的行并消除所有重复行而派生出一个结果表。当 ALL 随 INTERSECT 一起使用时 (INTERSECT ALL),不消除重复行。

使用外连接
left (outer) join
左外连接(左连接):结果集几包括连接表的匹配行,也包括左连接表的所有行。
right (outer) join
右外连接(右连接):结果集既包括连接表的匹配连接行,也包括右连接表的所有行。
full/cross (outer) join
全外连接:不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录。

分组:Group by
一张表,一旦分组 完成后,查询后只能得到组相关的信息。
组相关的信息:(统计信息) count,sum,max,min,avg 分组的标准)
在SQLServer中分组时:不能以text,ntext,image类型的字段作为分组依据
在selecte统计函数中的字段,不能和普通的字段放在一起;

去重
select distinct name from user

对数据库进行操作
分离数据库: sp_detach_db;
附加数据库:sp_attach_db 后接表明,附加需要完整的路径名

子查询(表名1:a 表名2:b)
select a,b,c from a where a IN (select d from b ) 或者: select a,b,c from a where a IN (1,2,3)

显示文章、提交人和最后回复时间
select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b

between的用法,between限制查询数据范围时包括了边界值,not between不包括
select * from table1 where time between time1 and time2
select a,b,c, from table1 where a not between 数值1 and 数值2

in 的使用方法
select * from table1 where a [not] in (‘值1’,’值2’,’值4’,’值6

数据库一些关键字的顺序
select distinct 字段名 from 表名
where …
group by …
having …
order by …
limit …

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值