2014年写sql中sql语句的变通
一、前言
最近在做我们公司的系统,在写sql语句上我感觉到我和老大们的差距,真的感觉到了,写一些嵌套的sql语句我还是不够逻辑啊!
二:下说说我要写的sql语句,这个模块是---专项工种的认定,说明白了就是技能的认定,这里分了三个TAB(认定0,撤换2,延期3),现在在认定模块认定了三条数据,我又在撤换模块撤换了其中一条数据,撤换的时候需要选择已经审核了的数据------->那么此时我可以选择的人是那些已经审核了的,但是要排除其中在撤换未审核、撤换中和延期未审核、延期中的数据,并且比如“张三”这条数据我认定了并且审核,然后我在撤换哪里撤换“张三”这条数据,并且这条数据也审核了,那么我在再点击撤换或者是延期哪里选人时张三这条数据就是撤换后的数据,而不是认定的那条数据,所以这里需要根据日期来选择最新的那条数据。
所以我第一次写的sql语句是这样的
select * from yz_zxgjbxx where shzt='2' and id not in (select swid from t_xx where ryzt in (2,3) and shzt in (0,1))
--ryzt-->认定状态
然后继续改进的sql是这样的
select * from t_xx c where c.pzrq = (select max(s.pzrq) from t_xx s where s.zf_id = c.zf_id) and c.shzt = '2' and c.id not in (select a.swid from t_xx a where a.ryzt in (2, 3) and a.shzt in (0, 1))
这里就是进行了嵌套。下面我们不用not in来表述:
select * from t_xxc,(select swid from t_xx where ryzt in (2, 3) and shzt in (0, 1) ) a where a.swid(+) = c.id and a.swid is null and c.pzrq = (select max(s.pzrq) from t_xx s where s.zf_id = c.zf_id) and c.shzt = '2'
嵌套里面的是右链接,这个sql里面的数据是我不想要的
select swid from t_xx where ryzt in (2, 3) and shzt in (0, 1)
所以有链接时右边数据全部显示,左边没有就补空,所以再加上条件,a,swid is null 就排除了上面select查找的数据,得到的就是我们需要的id来查找的数据。
三:今天才知道更新的语句还能这样写:
select * from table where t_id = '10957' for update
然后加锁直接修改数据。。。。。。。
四:oracle按照什么(desc,asc)排序只选取其中一条数据
select id,zid ,bz,from (select * from table t where zid =zid order by BGRQ desc) where rownum=1

浙公网安备 33010602011771号