MySQL D5

作者: 在海的那边有只小倩 | 来源:发表于2018-12-17 00:12 被阅读0次

    Inner Join 以foreign key为基准,只留下重合部分的数据

    SELECT column_name(s) FROM table_name1 INNER JOIN table_name2 ON table_name1.column_name=table_name2.column_name;

    Left Join

    SELECT column_name(s) FROM table_name1 LEFT JOIN table_name2 ON table_name1.column_name=table_name2.column_name;

    Right Join

    SELECT column_name(s) FROM table_name1 RIGHT JOIN table_name2 ON table_name1.column_name=table_name2.column_name;

    Full Join

    SELECT column_name(s) FROM table_name1 FULL JOIN table_name2 ON table_name1.column_name=table_name2.column_name

    注意:MySQL里没有Full Join语法,可以用Left Join+Right Join代替。

    Union

    SELECT column_name(s) FROM table_name1 UNION / UNION ALL SELECT column_name(s) FROM table_name2 注: UNION 操作符选取不同的值,UNION ALL 允许重复的值。  


    练习

    USE ClassicModels;

    1. 找出customer支付的check number, 如果没有check number, 也要保留customer (提示:Customers.customerNumber, Payments.checkNumber)

    2. 找出customer支付的check number, 如果没有check number,不用保留 customer (提示:Customers.customerNumber, Payments.checkNumber)

    3. 找出order number 对应的所有product line, 如果没有匹配,order number和product line也都要保留 (提示:OrderDetails.orderNumber, Products.productLine)

    USE ClassicModels;

    ## 找出customer支付的check number, 如果没有check number, 也要保留customer

    ## Customers.customerNumber, Payments.checkNumber

    SELECT*FROM customers;

    SELECT*FROM payments;

    SELECT customers.customerNumber, payments.checkNumber

    FROM customers LEFT JOIN payments ON customers.customerNumber=payments.customerNumber;

    ## 找出customer支付的check number, 如果没有check number,不用保留customer

    ## Customers.customerNumber, Payments.checkNumber

    SELECT customers.customerNumber, payments.checkNumber

    FROM customers Right JOIN payments ON customers.customerNumber=payments.customerNumber;

    ## 找出order number 对应的所有product line, 如果没有匹配,order number和product line也都要保留

    ## OrderDetails.orderNumber, Products.productLine

    SELECT orderdetails.orderNumber, products.productLine

    FROM orderdetails Left JOIN products ON orderdetails.productCode=products.productCode

    UNION

    SELECT orderdetails.orderNumber, products.productLine

    FROM orderdetails Right JOIN products ON orderdetails.productCode=products.productCode;

    相关文章

      网友评论

          本文标题:MySQL D5

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