2. 高級SQL

2018-02-24 15:51 更新

高級SQL

三表連接查找

mysql> select sales_rep.first_name, sales_rep.surname,
    -> value, customer.first_name, customer.surname
    -> from sales, sales_rep, customer where sales_rep.employee_number = sales.sales_rep
    -> and customer.id = sales.customer;

sales_rep表的employee_number與sales的sales_rep關聯(lián)
customer表的id和sales的customer相關,?構成了連接條件

  • 等值連接是一種內(nèi)連接, 通過兩個表或者多個表相等條件, 將兩個表的行組合到一個表中.(內(nèi)連接是連接的原始類型, 返回的每一行都包含來自每個表的數(shù)據(jù))
mysql> select ename, loc from emp, dept where emp.deptno = dept.deptno and emp.deptno = 10;

內(nèi)連接

#下面兩句是等價的
mysql> select first_name, surname, value from customer, sales where customer.id = sales.customer;
#注意inner join 表名 on 相關字段的SQL語句
mysql> select first_name, surname, value from customer inner join sales on customer.id = sales.customer;

左連接

左連接就是返回左邊匹配行, 不考慮右邊的表是否有相應的行.?返回匹配的全部行的必須是左表, left join關鍵字之前

#語法
select field1, field2 from table1 left join table2 on field1 = field2;
mysql> select first_name, surname, value from sales left join customer on id = customer;

右連接連接的順序與左連接相反

union鏈接

union用來把不同的select結果連接成一個, 每個語句必須有相同個數(shù)的列

union可能會進行去重處理, 不去重可以使用union all進行連接

union語句中order by是在整個union上進行的, 如果只想在某一個上使用可以請用小括號, union默認不返回重復記錄

#創(chuàng)建一個表用于union查詢
mysql> create table old_customer(
    -> id int,
    -> first_name varchar(30),
    -> surnamr varchar(40));
#插入數(shù)據(jù)
mysql> insert into old_customer values
    -> (5432, 'Thulani', 'Salis'),
    -> (2342, 'Shahiem', 'Papo');
#兩個查詢語句有相同的列
mysql> select id, first_name, surname from old_customer union select id, first_name, surname from customer;

查詢結果添加到另一個表

#創(chuàng)建一個用于插入的表
mysql> create table customer_sales_values(
    -> first_name varchar(30),
    -> surname varchar(40),
    -> value int);
mysql> insert into customer_sales_values(first_name, surname, value)
    -> select first_name, surname, sum(value) from sales natural join customer group by first_name, surname;
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號