SQL 常用操作

本文详细介绍了SQL语言的基础语法,包括查询、更新、插入等关键操作,涵盖了DISTINCT、WHERE、INSERT、UPDATE、DELETE等关键字的使用方法。同时,还讲解了JOIN、UNION、GROUP BY等高级特性,以及SQL约束、索引的创建与使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SQL语句

关键字

DISTINCT

用来返回唯一不同的列 select distinct name from student;

where

有条件的选取数据,对于文本值,使用单引号,数值不用引号!

select * from person where age=20    select * from person where name='jonh'
insert
insert into tbn values(....)   
insert into tbn(...) values(....)
update

delete用于删除表中的行

update person set name = 'ch',age=10 where ..
delete from person where ..
delete from person
top

Top 用于返回指定数目的列,并不是所有的数据库都支持

mysql-->limit  :select *from person limit 5
oracle-->top:
select top 2 * from person 
select top 50 percent from person 
like

模式匹配 like ‘%ch%

in

允许我们在 where字句中规定多个值!

    select  * from person where age in(1,2,3)
between

查找介于两者之间的数据,可以是数值文本或者日期(不同的数据库对开闭是不一样的)

    not  between  and
as

为表名或者列名定义别名

join

用来关联两个或者多个表,从多个表中获取数据

select * from person join man on person.id = man.id where ...
join:如果表中有一个匹配,则返回行
left join:即使右表没有匹配,也返回左表所有的行
left join:即使左表没有匹配,也返回右表所有的行
full join:即使左表没有匹配右表或者右表没有匹配左表,这些列都会被返回
union

用来合并结果集(查询列的顺序,数量,数据类型都要相同)

    union :返回不重复的
    union all:返回所有的 

select into :

    select * info copy from origin 
    向另外一个数据库拷贝表
    select * info copy in 'backup.db' from origin  where ...

SQL约束

not null:不接受null值
unique:唯一约束(primary key自动定义唯一约束)
create person {
    _id int not null,
    unique(_id)
}
alter

用于操作表在的列

table persons add unique(_id)
alter table person add colnum_name int
alter table person drop colnum_name 
primary key foreign key

primary key 每个表都有且仅有一个not null的主键,可以指定多个列为一个主键
foreign key:外建指定另外一张表的主键,防止非法数据插入外建列

create person {
    _id int not null,
    userId int ,
    foreign key(userId) references Person(_id)
}
check

用来约束列的取值范围 default指定默认的值

    create person {
        userId int  default,
        check(userId > 0)
    }
index
创建索引,加快查询速度
CREATE INDEX user_index ON RECORD(USER_ID)
创建复合索引
CREATE INDEX group_index ON RECORD(USER_ID,GROUP_ID)
drop

删除表,索引,数据库

drop index index_name on person
drop table person
drop database person
truncate table person 只删数据,不删表本身

通配符:

SQL函数

max,min ,count,avg,sum....
having:
group by:分组,比如查询每个国家由多少人:
select country,count(*) from P group by country!
select name,sum(price) from P group by name

having

由于where不能与函数一起使用,所以使用having
查询表中消费金额大于2000的人

select name,sum(price) from P where name = 'ch' group by name having sum(price) > 2000

通配符

%:匹配一个或者多个字符
_:代替一个字符
[] [!]:匹配任意一个字符

connect by:用于父子关系的递归查询

优化与改善数据库性能:

1.SQL格式化
2.调整From字句表的顺序:
通常把较大的表放在后面会有更好的性能
3.结合的顺序:
一般将基表放在结合的右侧,要被结合的表从小到大排列
from t1,t2,t3 (t1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值