数据库常用语法示例

1. 显示查询结果使用排序功能

order by [列名] desc; #desc 表示降序,asc 表示升序
select * from 表名 where ID = '001' order by createtime desc;
--createtime(创建时间) ,默认显示时间为升序,使用order by [列名] desc 转为降序显示

2. 把多条查询语句结果显示在一个窗口:union all
---例:把下面3条结果显示在同一窗口------

select * from 表名 where ID = '001' union all
select * from 表名 where ID = '002' union all
select * from 表名 where ID = '003'

3.多表关联查询:select * from 表1 where ID in (select ID from 表2 )

select * from 表1 where ID in (select ID from 表2)

4.数据库版本查看

select * from v$version;

5.删除表里面的某一行 delete from 表名 where 条件1 。。。

delete from 表名 where ID= '001'
select * from 表名 where ID ='001'    --提示:删除前先使用select 语句确认删除的条件是否唯一

6.修改表里面的内容

update 表名 set 修改后内容 where 条件1 。。。
update 表名 set ID = '002' where ID = '001' ; --把001修改为002

7.替换函数replace(字段名,'源','目的')

1.先select 字段名,replace(字段名,'_00_','_01_') from 表名 where 条件1 …
2.update 表名 set 字段名=replace(字段名,'_00_','_01_') where 条件1 …

--替换指定内容
--查询
select name,replace(name,'old','new') from 表名1 where 条件1 。。。
--替换
update 表名1 set name=replace(name,'old','new') where 条件1 。。。

8.时间计算问题:

--以2018年3月7日为例,加90天 2018-06-05 00:00:00
select to_date('2018-03-07 00:00:00','yyyy-MM-dd hh:mi:ss')+90 from dual; --精确到时分秒
select to_date('2018-03-07','yyyy-MM-dd')+90 from dual; --不加时分秒

9.distinct去重后再count(*)

SELECT COUNT(*) AS test FROM ,test(自定义的名称)
SELECT COUNT(*) AS test FROM (select distinct id from users where date >='20160101' and date <= '20171231' and ID in (10,20,30,40,60))

10.从查询出来的结果再从中查询

--from 接前一次查询的结果
select * from (select 字段1,字段2,字段3 from 表名 where a =3) where ID= '001'

11.截取后n位

substr(字段名,length(字段名)-n + 1 ,n )
select substr('字段名',length('字段名')-n+1,n) from dual;
--当 n=6 :
select substr('字段名',length('字段名')-6+1,6) from dual;

12.group by + order by count(*) # 统计重复的数量并排序

select  count(*) from  user  GROUP BY name ORDER BY count(*)       #升序
select  count(*) from  user  GROUP BY name ORDER BY count(*) desc  #降序

13.between 1 and 4 等于 in (1,2,3,4)

select  * from user where  id BETWEEN 1 and  4

14.instr 找出分段内容(如:name = 一级/二级/三级) , 以 / 为分隔,找出 一级分类并排序

group by substr(name,0,instr(name,'/')-1) order by count(*) desc

15.只显示查询出来结果的第一行 rownum=1


16.ROWNUM< 50 只显示前49行

SELECT * FROM 表名 WHERE ROWNUM< 50

17.修改某个字段的精度

alter table 表名 modify 列名 数据类型;
alter table users modify zcmc varchar2(120);
posted @ 2022-10-13 09:07  此生逍遥py  阅读(36)  评论(0)    收藏  举报