数据库(2)

子查询

  • 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);

主键、外键和索引的区别

  • 主键具有唯一性,只能标识一条记录 不允许为空
  • 外键是另一个表的主键,外键可以重复,并且可以是空值
  • 外键用于和其他表建立联系 一个表可以有多个外键
  • 索引字段没有重复值,但可以是空值,提高查询排序的速度

聚集索引和非聚集索引的区别

  • 聚集索引一定是唯一索引。但唯一索引不一定是聚集索引。
  • 聚集索引,在索引页里直接存放数据,而非聚集索引在索引页里存放的是索引,这些索引指向专门的数据页的数据。

猜你喜欢

转载自blog.csdn.net/wlm_suzhou/article/details/78184365