联结表

作者: olivia_ong | 来源:发表于2016-11-15 19:59 被阅读0次

    一些定义

    联结(join)

    将数据分成多个表进行有效的存储,并通过外键联结彼此。

    联结的好处
    • 方便处理;
    • 有更大的可伸缩性;(能够适应不断增加的工作量而不失败)
    笛卡尔积

    一个表和另一个表的交叉相乘,返回的行数是一个表的行数乘以另一表的行数

    创建联结

    select vend_name,prod_name,prod_price 
    from vendors,products 
    where vendors.vend_id=products.vend_id;//等值联结
    

    没有联结条件(where子句)的表返回的是笛卡尔积。

    内部联结(inner join)

    使用关键字inner join,后面联结条件前不用where用on

    select vend_name,prod_name,prod_price 
    from vendors inner join products 
    on vendors.vend_id=products.vend_id;
    =select vend_name,prod_name,prod_price 
    from vendors natural join products 
    where vendors.vend_id=products.vend_id;//自然联结,至少应该有一行出现在不止一个表中
    

    外部联结

    该联结包含了哪些在相关表中没有关联行的行

    table1 left (outer) join table2 on...
    =table2 right (outer) join table1 on...//left和right表示指定哪边的表检索所有行
    

    自联结

    替代从相同表中检索数据的子查询

    select p1.prod_id,p1.prod_name 
    from products as p1, products as p2
    where p1.vend_id=p2.vend_id 
    and p2.prod_id='dtntr';
    

    使用带聚集函数的联结

    select customers.cust_name,
        customers.cust_id,
        count(orders.order_num) as num_ord 
    from customers inner join orders on customers.cust_id=orders.cust_id
    group by customers.cust_id;
    

    相关文章

      网友评论

          本文标题:联结表

          本文链接:https://www.haomeiwen.com/subject/krdlpttx.html