SQL 連線查詢

2021-10-06 18:18:37 字數 3171 閱讀 1122

#連線查詢

含義:又稱多表查詢,當查詢的字段來自於多個表時,就會用到連線查詢

笛卡爾乘積現象:

表1 有m行,表2有n行,結果=m*n行

發生原因:沒有有效的連線條件

如何避免:新增有效的連線條件

select name,boyname from boys,beauty

where beauty.`boyfriend_id`=boys.id;

分類:按年代分類:sq192標準:僅僅支援內連線

sq199標準:支援內連線+外連線(左外和右外)+交叉連線

按功能分類:

內連線:等值連線、非等值連線、自連線

外連線:左外連線、右外連線、全外連線

交叉連線

一、內連線

①等值連線:

語法: select 查詢列表

from 表名1 別名1,表名2,別名2

where 等值連線的連線條件

特點: 1、為了解決多表中的欄位名重名問題,往往為表起別名,

提高語義性

2、表的順序無要求

#一、簡單的兩表連線

use `myemployees`

#查詢員工名和部門名

select e.last_name,d.`department_name`

from `employees` e,`departments` d

where e.`department_id`=d.`department_id`;

#二、新增篩選條件

#查詢部門編號》

100的部門名和所在的城市名

select `department_name`,`city`

from `departments` d,`locations` l

where d.`location_id`=l.`location_id`

and d.`department_id`>

100;

#查詢有獎金的員工名、部門名

select `last_name`,`department_id`

from `departments` d,`employees` e

where d.`department_id`=e.`department_id`

and e.`commission_pct` is not null

;#查詢城市名彙總第二個字元為o的部門名和城市名

select `department_name`,`city`

from `departments` d,`locations` l

where d.`location_id`=l.`location_id`

and city like '_o%'

;#三、新增分組+篩選

#查詢每個城市的部門個數

select count(*

) 部門個數,l.`city`

from `departments`d,`locations` l

where d.`location_id`=l.`location_id`

group by l.`city`;

#②非等值連線

#查詢部門編號在10

-90之間的員工的工資級別,並按級別進行分組

select count(*

) 個數,grade

from `employees` e

join sal_grade g

on e.`salary` between g.`min_salary` and g.`max_salary`

where e.`department_id` between 10 and 90

group by g.grade;

#③自連線

#查詢員工名和對應的領導名

select e.`last_name`,m.`last_name`

from `employees` e

join `employees` m

on e.`manager_id`=m.`employee_id`;

#二、外連線

說明:查詢結果為主表中所有的記錄,

如果從表有匹配項,則顯示匹配項;

如果從表中沒有匹配項,則顯示null

應用場景:一般用於查詢主表中有但從表沒有的記錄

特點:1、外連線分主從表,兩表的順序不能任意調換

2、左連線,左為主表。右連線,右為主表。

語法:select 查詢列表

from 表1 別名

left|right|full [outer] join 表2 別名

on 連線條件

where 篩選條件;

use girls;

#查詢所有女神記錄,以及對應的男神名,如果沒有對應的男神,則顯示為null

#左連線

select b.

*,bo.

*from beauty b

left join boys bo on b.`boyfriend_id`=bo.`id`;

#右連線

select b.

*,bo.

*from boys bo

right join beauty b on b.`boyfriend_id`=bo.`id`;

#查詢哪個女神沒有男朋友

#左連線

select b.`name`

from `beauty` b

left join boys bo on b.`boyfriend_id`=bo.`id`

where bo.`id`;

#右連線

select b.

*,bo.

*from boys bo

right join `beauty` b on b.`boyfriend_id`=bo.`id`

where bo.`id` is null

;#查詢哪個部門沒有員工,並顯示其部門編號和部門名

select count(*

) 部門個數

from departments d

left join `employees` e on d.`department_id`=e.`department_id`

where e.`employee_id` is null

;

SQL 連線查詢

連線查詢是指乙個查詢同時涉及到兩個及以上的表。包括 等值連線,自然連線,非等值連線,自身連線,外連線,復合查詢.等.color red size large 1.等值連線 於非等值連線 size color 查詢每個學生及選課的情況 select student.sc.from student,sc...

sql連線查詢

sql連線查詢的連線查詢分為交叉連線 內連線 外連線。以下面兩張表為例演示連線查詢。a表 b表 分為左連線 右連線 完全外連線 左連線 left join 或left outer join select from a left outer join b on a.aid b.bid返回結果 返回a表...

SQL連線查詢

筆記區 多表連線查詢 1,等值連線 select from table1,table2 where table1.t1no table2.t2no 2,非等值 笛卡爾積 特點 查詢個數為乘積 作用 模擬大量資料 交叉連線 自連線內連線 把符合條件的查出來 以上都是內查詢 外連線 可以把不存在員工的部...