SQl CookBook记录
检索记录
-
检索行和列
- 部分行
- 条件行
-
SELECT中使用条件
case when ...
chen ...
else ...
end
-
case
-
-
返回限制的行数
DB2-----------------------select * from emp fetch first 5 rows only
MySQL PostgreSQL ---------select * from emp limit 5
Oracle -------------------select * from emp where rownum <=5(ROWNUM是在获取每行之后才赋予的)
SQL Server----------------select top 5 * from emp
-
随机返回n条记录
DB2 --------------------- select * from emp order by rand() fetch first 5 rows only
MySQL-------------------- select * from emp order by rand() limit 5
PostgreSQL--------------- select * from emp order by random() limit 5
Oracle------------------- select * from (select * from emp order by dbms_random.value()) where rownum <= 5
SQL Server--------------- select top 5 * from emp order by newid()
- order by
-
按模式搜索
select * from emp where deptno in (10,20)
select * from emp where ename like '%I%' or job like '%ER'
- in
- like
-
检索列
- 部分列
- 为列取名称
-
WHERE中引用取别名的列
将查询作为内联视图
select * from
(select sal as salary, comm as commission from emp) x
where salary < 5000
-
内联视图
-
-
连接列值
DB2,Oracle, PostgreSQL --- ||
MySQL -------------------- concat()
SQL server --------------- +
-
空值
-
查找空值
select * from emp where comm is null
-
IS NULL
-
-
转换空值
select coalesce(comm,0) from emp
select case
when comm is null then 0
else comm
end
from emp
-
COALESCE()
-
CASE
-
-