SQL.Cookbook 读书笔记1 查询

本文内容摘自 SQL.Cookbook 一书

第一章 select

1.1 按条件查询

select * from emp where deptno = 10 or comm is not null or sal <= 2000 and deptno = 20;

1.2 给查询的列起个有意义的名字

select sal as salary,comm as commission from emp;

将别名放在内联视图中即可在

select * from (select sal as salary,comm as commission from emp)
x where salary < 2000;

x 为内联视图别名 有的数据库要别名才行 SQL的执行顺序是 先执行from后面的内容 在执行 where后面的内容 最后执行select后面的内容 所以定义先后要注意

1.3 将多个列值连接成一列 这个可以用于服务器下生成批量执行的命令

select ename||' WORK AS A '||job as msg from emp where deptno = 0;

MYsql 可以用concat函数

select concat(ename,' WORK AS A ' ,job) as msg from emp where deptno = 10;

1.4 使用条件逻辑 case表达式根据查询出结果执行条件逻辑

select ename,sal,
    case when sal <= 2000 then 'UNDEPARD'
         when sal >= 4000 then 'OVERPARD'
         else 'OK'
    end as status
from emp;

status 是case的别名 如果不写else 在2000 到4000范围的值status的值是NULL

1.5 限制查询返回的条数

MYSQL

select * from emp limit 5;

ORACLE

select * from emp where rownum <=5;

1.6 从表中随机返回n条数据

MySQL

select ename,job from emp order by rand() limit 5;

ORACLE

select * from (select ename,job from emp order by dbms_random.value()) where rownum <= 5;

1.7 将NULL值替换

select  coalesce(comm,0) from emp; -- if comm isn't null return comm

1.8 模糊查询

select ename,job from emp where deptno in (10,20) and (ename like '%I%' or job like '%ER'); 

% 放在前面表示ER为结尾

posted on 2015-01-22 13:05  weiguoyuan  阅读(228)  评论(0)    收藏  举报

导航