取前几条数据
MSSQL
如在ms sqlserver 用此语句:
select top 2 * from test01 就会只显示前2条记录,
MYSQL
select * from your_table limit 2
使用limit就可以了.
Oracle的语句:
select * from (select rownum r ,* from test) tt
where tt.r > 50 and tt.r <= 100; (最好用PLSQL游标来解决)
DB2中:
select * from payment fetch first 5 row only --查前5条记录
oralce 分页查询
从第11条到第20条
select * from (
select row_.*, rownum rownum_ from (
select person_id, chn_name, chn_firstname_py from t_pbase_info
) row_ where rownum <=20
) where rownum_ >=11
oralce 左右内全连接
- --建立测试数据
- create table a(id number);
- create table b(id number);
- insert into a values(1);
- insert into a values(2);
- insert into a values(3);
- insert into b values(1);
- insert into b values(2);
- insert into b values(4);
- commit;
- --左:
- --主流数据库通用的方法
- select * from a left join b on a.id=b.id;
- --Oracle特有的方法
- select * from a, b where a.id=b.id(+);
- ID ID
- ---------- ----------
- 1 1
- 2 2
- 3
- --右:
- --主流数据库通用的方法
- select * from a right join b on a.id=b.id;
- --Oracle特有的方法
- select * from a, b where a.id(+)=b.id;
- ID ID
- ---------- ----------
- 1 1
- 2 2
- 4
- --内
- --主流数据库通用的方法
- select * from a join b on a.id=b.id;
- --where关联
- select * from a, b where a.id=b.id;
- ID ID
- ---------- ----------
- 1 1
- 2 2
- --全外
- --主流数据库通用的方法
- select * from a full join b on a.id=b.id;
- --Oracle特有的方法
- select *
- from a, b
- where a.id = b.id(+)
- union
- select *
- from a, b
- where a.id(+) = b.id;
- ID ID
- ---------- ----------
- 1 1
- 2 2
- 3
- 4
- --完全,也叫交叉连接或者笛卡尔积
- --主流数据库通用的方法
- select * from a,b;
- --或者
- select * from a cross join b;
- ID ID
- ---------- ----------
- 1 1
- 1 2
- 1 4
- 2 1
- 2 2
- 2 4
- 3 1
- 3 2
- 3 4
- 连接无非是这几个
- --内连接和where相同
- inner join
- --左向外连接,返回左边表所有符合条件的
- left join
- --右向外连接,返回右边表所有符合条件的
- right join
- --完整外部连接,左向外连接和右向外连接的合集
- full join
- --交叉连接,也称笛卡儿积。返回左表中的每一行与右表中所有行的组合
- cross join
- --补充:
- --左向外连接,返回左边表所有符合条件的,
- --注意这里没有第二个加号,会直接过滤掉数据,只显示符合条件的记录
- select *
- from a, b
- where a.id = b.id(+)
- and b.id = 2;
- ID ID
- ---------- ----------
- 2 2
- --左向外连接,返回左边表所有符合条件的
- --注意where上第二个加号,它的作用是修改右边表记录的显示,例如如果b.id(+) = 2,显示为2,否则显示null
- select *
- from a, b
- where a.id = b.id(+)
- and b.id(+) = 2;
- ID ID
- ---------- ----------
- 2 2
- 3
- 1
-
- order by group by 区别
-
order by 排序查询、asc升序、desc降序 示例: select * from 学生表 order by 年龄 查询学生表信息、按年龄的升序(默认、可缺省、从低到高)排列显示 也可以多条件排序、 比如 order by 年龄,成绩 desc 按年龄升序排列后、再按成绩降序排列 group by 分组查询、having 只能用于group by子句、作用于组内,having条件子句可以直接跟函数表达式。使用group by 子句的查询语句需要使用聚合函数。 示例: select 学号,SUM(成绩) from 选课表 group by 学号 按学号分组、查询每个学号的总成绩 select 学号,AVG(成绩) from 选课表 group by 学号 having AVG(成绩)>(select AVG(成绩) from 选课表 where 课程号='001') order by AVG(成绩) desc 查询平均成绩大于001课程平均成绩的学号、并按平均成绩的降序排列