4.1带In 关键字的子查询
一个查询语句的条件可能落在另一个SELECT 语句的查询结果中。
SELECT * FROM t_book WHERE booktypeId IN (SELECT id FROM t_booktype);
SELECT * FROM t_book WHERE booktypeId NOT IN (SELECT id FROM t_booktype);
4.2 带比较运算符的子查询
子查询可以使用比较运算符。
SELECT * FROM t_book WHERE price>=(SELECT price FROM t_pricelevel WHERE priceLevel=1);
4.3 带Exists 关键字的子查询
假如子查询查询到记录,则进行外层查询,否则,不执行外层查询;
SELECT * FROM t_book WHERE EXISTS (SELECT * FROM t_booktype);
SELECT * FROM t_book WHERE NOT EXISTS (SELECT * FROM t_booktype);
4.4 带Any 关键字的子查询
ANY 关键字表示满足其中任一条件;
SELECT * FROM t_book WHERE price>= ANY (SELECT price FROM t_pricelevel);
4.5 带All 关键字的子查询
ALL 关键字表示满足所有条件;
SELECT * FROM t_book WHERE price>= ALL (SELECT price FROM t_pricelevel);
合并查询结果
5.1 UNION
使用UNION 关键字是,数据库系统会将所有的查询结果合并到一起,然后去除掉相同的记录;
SELECT id FROM t_book UNION SELECT id FROM t_booktype;
5.2 UNION ALL
使用UNION ALL,不会去除掉系统的记录;
SELECT id FROM t_book UNION ALL SELECT id FROM t_booktype;
为表和字段取别名
6.1 为表取别名
格式: 表名 表的别名
SELECT * FROM t_book t WHERE t.id=1;
SELECT t.bookName FROM t_book t WHERE t.id=1;
6.2 为字段取别名
格式: 属性名 [AS] 别名
SELECT t.bookName bName FROM t_book t WHERE t.id=1;
SELECT t.bookName AS bName FROM t_book t WHERE t.id=1;