SQL学习指南 笔记
1 条件类型
1.1 相等条件
SELECT pt.name product_type, p.name product
FROM product p INNER JOIN product_type pt
ON p.product_type_cd = pt.product_type_cd
WHERE pt.name = 'Customer Accounts'
1.2 范围条件
SELECT emp_id, fname, lname, start_date
FROM employee
WHERE start_date < '2007-01-01';
between操作符
/*范围的上下限是闭合的*/
SELECT emp_id, fname, lname, start_date
FROM employee
WHERE start_date BETWEEN '2002-01-01' AND '2003-01-01';
字符串范围
SELECT cust_id, fed_id
FROM customer
where cust_type_cd = 'I'
and fed_id BETWEEN '500-00-0000' AND '999-99-9999'
1.3 成员条件
/*有限值集合*/
SELECT account_id, product_cd, cust_id, avail_balance
FROM account
WHERE product_cd IN ('CHK','SAV','CD', 'MM');
使用子查询
/*'CHK','SAV','CD', 'MM'的product_type_cd列都为'ACCOUNT' */
SELECT account_id, product_cd, cust_id, avail_balance
FROM account
where product_cd in (SELECT product_cd FROM product
WHERE product_type_cd = 'ACCOUNT');
1.4 匹配条件
select lname
from employee
where lname like '_a%e%'
使用正则表达式
/*lname以F或G打头的*/
SELECT emp_id, fname, lname
from employee
WHERE lname REGEXP '^[FG]';
2 null:4个字母的关键字
使用null时,需要记住:
- 表达式可以为 null, 但不能等于 null
- 两个 mill 值彼此不能判断为相等
SELECT emp_id, fname, lname, superior_emp_id
FROM employee
WHERE superior_emp_id IS NULL;
/*不能等于 null*/
SELECT emp_id, fname, lname, superior_emp_id
FROM employee
WHERE superior_emp_id = NULL;
查找所有不是 Helen Fleming (employee ID为6)所管理的雇员
SELECT emp_id, fname, lname, superior_emp_id
FROM employee
WHERE superior_emp_id != 6;
雇 员 Michael Smith ,他 的superior_emp_id 列为 null (因为他是银行的高层人物)没有列出来
SELECT emp_id, fname, lname, superior_emp_id
FROM employee
WHERE superior_emp_id != 6 OR superior_emp_id IS NULL;