数据库(2)
来源:互联网 发布:网络硬盘录像机的用途 编辑:程序博客网 时间:2024/05/22 20:28
子查询
- select cust_id from orders where order_num in (select order_num from orderitems where prod_id=’TNT2’);
- 在select语句中,子查询总是从内向外处理
- 作为计算字段使用子查询 假设需要显示customers表中每个客户的订单总数,订单与相应的客户ID存储在ordrs表中
为了执行这个操作,需要
1)从customers表中检索客户列表 2)对于检测出的每个客户,统计其在orders表中的订单数目
对客户10001的订单进行计数:select COUNT(*) AS orders from orders where cust_id=10001
为了对每个客户执行COUNT()计算,应该将COUNT()作为一个子查询
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 vend_name, prod_name,prod_price from vendors,products where venders.vend_id = products.vend_id order by vend_name,prod_name;
- 笛卡尔积 由没有联结条件的表关系返回的结果为笛卡尔积,检索出的行的数目将是第一个表中的行数乘以第二个表中的函数
使用不同的类型的联结
- 内部联结
- 自联结
- 自然联结
- 外部联结
内部联结
- select customers.cust_id,orders.order_num from customers insert join orders on customers.cust_id = orders.cust_id;
外部连接
- select customers.cust_id,orders.order_num from customers left outer join orders on customers.cust_id = orders.cust_id
- 外部联结与内部联结的区别在于还包括没有关联行的行
使用连接和外部连接
- 注意使用的联结类型,一般我们使用内部联结,但使用外部联结也是有效的
- 保证使用正确的联结条件,否则将返回不正确的数据
- 应该总是提供连接条件,不然会得出笛卡尔乘积
- 在一个联结中可以包含多个表
组合查询
- union 组合多种查询条件 即多个select语句
- union的每个查询必须包含相同的列,表达式或聚集函数
- union会自动去除重复的行
- 如果不想去除重复的行可以使用union all
插入数据
- insert into table() … values ();
更新和删除数据
- update 更新表中特定行
- 更新表中所有行
- update customers set cust_email=”where cust_id =*
- delete 删除一行
- delete from customers where id=*
修改表
- alter table vendors add vend_phone char(20);
- alter table vendors drop column vend_phone;
- 建立外键:alter table orders add constraint fk_orders_customers foreing key (cust_id) references customers(cust_id);
主键、外键和索引的区别
- 主键具有唯一性,只能标识一条记录 不允许为空
- 外键是另一个表的主键,外键可以重复,并且可以是空值
- 外键用于和其他表建立联系 一个表可以有多个外键
- 索引字段没有重复值,但可以是空值,提高查询排序的速度
聚集索引和非聚集索引的区别
- 聚集索引一定是唯一索引。但唯一索引不一定是聚集索引。
- 聚集索引,在索引页里直接存放数据,而非聚集索引在索引页里存放的是索引,这些索引指向专门的数据页的数据。
阅读全文
0 0
- 数据库理论(2)之数据库事务
- Oracle数据库(关系型数据库2)
- 数据库(2)
- 数据库复习(2)
- 数据库基础(2)
- Mysql数据库(2)
- MySQL数据库(2)
- 数据库--(2)
- 数据库学习(2)
- 数据库day01(2)
- 数据库(2)---完整性
- 数据库(2)
- 【数据库系统概论】-关系数据库标准语言SQL(2)
- 【数据库系统概论】-关系数据库理论(2)
- 数据库事务(2)数据库的隔离级别
- 数据库里程(2):数据库的隔离机制
- vc数据库编程(2)
- ODBC数据库接口(2)
- spin and mutex lock
- push本地代码到github出错
- layer.close()关闭进度条和Iframe窗
- HDU 1254 推箱子(双重bfs)
- Java post请求发送json数据在filter中解析方法
- 数据库(2)
- linux操作shell脚本定义数组赋值取值
- 从源码的角度解析Android异步消息处理机制
- TCP通信的三次握手和四次撒手的详细流程
- jQuery中attr()和prop()的区别
- Runloop详解
- Markdown编辑器基础用法
- Sublime Text 3 安装ctags58
- hdu 2807 矩阵相乘+弗洛伊德