数据库检索(Select)
2016-11-15 本文已影响0人
olivia_ong
基本检索
- 检索单个列
select column_name from table_name;
- 检索多个列
select column_name1,column_name2,... from table_name;
- 检索所有列(整个表)
select * from table_name;
带有特定功能的检索
- 检索不同的行(即返回一个列中列值不同的行)
select distinct column_name
from table_name;
- 排序检索
1.升序排序
select column_name1
from table_name
order by column_name2;//按照column_name2对column_name1排序
2.降序排序
select column_name1
from table_name
order by column_name2 desc;
- 限制输出行数
select column_name from table_name limit offset;//从第一行开始返回不超过offset行
select column_name from table_name **limit** begin,n;//从begin+1行开始检索n行(begin从0开始)
=select column_name from table_name **limit** n **offset** begin;
嵌套检索(子查询)
嵌套在其他查询中的查询
- 一般子查询
select cust_id
from orders
where order_num in ( select order_num
from orderitems
where prod_id='TNT2');
- 相关子查询
涉及外部查询的子查询
select cust_name,
cust_state,
(select count(*)
from orders
where orders.cust_id=customers.cust_id) as orders
from customers
order by cust_name;
组合查询
- 执行多个select并将结果作为单个查询结果集返回。利用union关键字将select语句连起来,每个查询必须包含相同的列,表达式或聚集函数。union自动去除重复的行。
select vend_id,prod_id,prod_price
from products
where prod_price<=5
union
select vend_id,prod_id,prod_price
from products
where vend_id in (1001,1002);
- 对组合查询结果排序,只能够使用一个order by语句,可以用其来排序所有结果。