网站首页mysql
oracle下常用SQL记录
发布时间:2018-11-14 10:53:36编辑:hover阅读(3148)
习惯了mysql的轻巧敏捷,不太清楚同样的SQL查询在oracle下为何要这么麻烦,如下:
1. 和mysql类似的分页, 取第20-30行记录
mysql的分页sql:
select * from table limit 20, 10;
oracle相同的分页sql:
select * from ( select a.*, rownum rn from ( #原mysql分页语句, 去掉limit; select * from table ) a where rownum<=( 20+10) ) where rn>20;
2. 分组取首行
#mysql直接group后,就是首行 SELECT * FROM table GROUP BY field
oracle的分组:
SELECT * FROM (SELECT ROW_NUMBER() OVER(PARTITION BY x ORDER BY y DESC) rn, table.* FROM table) WHERE rn = 1 ;
3. 多表关联更新
mysql的多表更新:
UPDATE table1 a,table2 b SET a.field1 = b.field1, a.field2 = b.field2 WHERE a.field3 = b.field3;
oracle的多表更新:
UPDATE table1 a SET (field1, field2) = ( SELECT b.field1, b.field2 FROM table2 b WHERE b.field3 = a.field3 ) WHERE EXISTS ( SELECT 1 FROM table2 b WHERE b.field3 = a.field3 );
4.删除多余重复行
mysql
DELETE FROM table WHERE name IN ( SELECT t.name FROM ( SELECT name FROM table GROUP BY name HAVING count(1) > 1 ) t ) AND id NOT IN ( SELECT dt.minId FROM ( SELECT min(id) AS minId FROM table GROUP BY name HAVING count(1) > 1 ) dt )
oracle
DELETE FROM table AS ta WHERE ta.id <> ( SELECT t.maxId FROM ( SELECT max( tb.id ) AS maxId FROM table as tb WHERE ta.name = tb.name ) t );
评论