zoukankan      html  css  js  c++  java
  • T-Sql(四)表关联和视图(view)

      今天讲下T-sql中用于查询的表关联和视图,我们平时做项目的时候会遇到一些复杂的查询操作,比如有班级表,学生表,现在要查询一个学生列表,要求把学生所属班级名称也查询出来,这时候简单的select查询就不行了,需要关联班级表,因为学生是一定属于某一个班级的,所以关联的示例需要自关联。

      表关联(join)  

      下面列一些示例代码,帮助大家理解。

    select t2.*         --表自关联
    from Tree t1
    inner join Tree t2
    on t1.NO=t2.ParentNo
    where t1.Name='Node1_2';
    
    select * from tree      --子嵌套查询
    where ParentNo = (select NO from tree where Name = 'Node1_2');
    
    select * from tree 
    where parentNo in (select no from tree where Name = 'Node1_2');

      上面是表自关联,关键字inner,就是返回t1.NO=t2.ParentNo条件的所有t2表的数据,

      有表自关联,当然还有左关联,右关联,示例代码:

    select t2.*         --左关联
    from Tree t1
    left join Tree t2
    on t1.NO=t2.ParentNo
    where t1.Name='Node1_2';
    
    select t2.*         --右关联
    from Tree t1
    right join Tree t2
    on t1.NO=t2.ParentNo
    where t1.Name='Node1_2';

      视图View

      视图的关键字是View,就是一个查询集合,方便我们去查询数据,视图其实就是表,多表连接的表,我们查询的时候不需要反复的去拼接语句,直接查询视图就可以,方便我们的操作,当然一些简单的查询操作就没必要去创建视图了。

      示例代码:

    create view Production.vw_Product
    as 
        select t1.* from Production.Product t1
        left outer join Production.ProductModel t2 on t2.ProductModelID=t1.ProductModelID
        left outer join Production.ProductSubcategory t3 on t3.ProductSubcategoryID=t1.ProductSubcategoryID
        left outer join Production.UnitMeasure t4 on t4.UnitMeasureCode=t1.SizeUnitMeasureCode and t4.UnitMeasureCode=t1.SizeUnitMeasureCode
        --order by t1.ProductID
        

      查询视图:

    select *from Production.vw_Product

      表关联和视图都是比较简单的数据库操作,但也是比较常用的。大家好好练习。

      还有一些相关编程知识的整理,希望大家关注下。。。

  • 相关阅读:
    [zz]Ubuntu源签名错误/Ubuntu 更新源签名错误 –BADSIG 40976EAF437D05B5
    [zz]GNU C __attribute__ 机制简介
    [zz]为小米创建虚拟机路由器
    liburcu 库
    多代理集群调度:可伸缩性和灵活性
    automake的使用速查
    automake之简单的例子
    ajax原生
    Cookie 和Session 的原理
    路径问题
  • 原文地址:https://www.cnblogs.com/xishuai/p/3373562.html
Copyright © 2011-2022 走看看