mysql多表查詢

2021-10-07 07:56:12 字數 2910 閱讀 7789

語法:select 欄位1 [,欄位n] from 表1,表2 [,表n]

select

*from category, produce

交叉查詢會產生笛卡爾積,表與表之間的連線相當於是在做乘法運算,運算結果很多記錄都是無意義的。(盡量少用)

格式:select 欄位1 [,欄位n] from 表1,表2 [,表n] where 連線條件

select

*from category c, produce p where c.cid = p.c_id;

格式:select 欄位1 [,欄位n] from 表1 [inner] join 表2 on 表1.欄位 = 表2.欄位

select

*from category c join product p on c.cid = p.c_id;

格式:select 欄位1 [,欄位n] from 表1 left [outer] join 表2 on 表1.欄位 = 表2.欄位

左外連線查詢是以left outer join 語句左邊的表為基準表,保證左表資料完整,如果右表沒有與左表資料匹配的記錄,那麼右表將以一條null資料填充查詢結果,保證左表的完整。

格式:select 欄位1 [,欄位n] from 表1 right [outer] join 表2 on 表1.欄位 = 表2.欄位

右外連線查詢是以right outer join語句右邊的表為基準表,保證右表資料完整,如果左表沒有與右表資料匹配的記錄,那麼左表將以一條null資料填充查詢結果,保證右表的完整。

小練習:

-- 查詢**在一萬以內名字中包含 '想' 的商品所有資訊(包括分類資訊)

select

*from category c inner

join product p on c.cid = p.c_id where p.price <

10000

and p.pname like

'%想%'

;-- 查詢所有分類商品的個數

select c.cid,

count

(p.pid)

from category c left

outer

join product p on c.cid = p.c_id group

by c.cid;

一條select語句結果作為另一條select語法一部分(查詢條件,查詢結果,表等)

語法:

select 欄位1 [, 欄位n ] from 表1 [, 表n ]

where 欄位1 operator操作符

(select 欄位1 [, 欄位2] from 表1 [, 表2] [where 條件])

-- 1.先查詢海爾洗衣機的** 記錄下28512

select price from product where pname like

'%海爾%洗衣機%'

;-- 2.查詢**為28512的商品

select

*from product where price =

28512

;

-- 方法二:子查詢在作為條件在where條件部分

select

*from product where price in

(select price from product where pname like

'%海爾%洗衣機%'

);

把一條sql語句的查詢結果當做條件值傳入到另一條sql語句中,此時海爾洗衣機這條sql返回乙個結果,這種叫單行單列子查詢

-- 方法三:子查詢作為臨時表在from後

select p.

*from product p join

(select price from product where pname like

'%海爾%洗衣機%'

) t on p.price = t.price;

select

*from category where cid in

(select

distinct c_id from product)

;

查詢部分返回了多條記錄,這種子查詢叫做單行多列子查詢

select

*from

(select c.cname, p.

*from product p join category c on p.c_id=c.cid) a where a.price >

100;

把乙個查詢結果直接封裝為乙個虛擬表a表,然後在封裝的虛擬表a表的基礎上又做查詢,這種子查詢叫做多行多列子查詢

mysql多表 MySQL 多表查詢

多表查詢 select listname from tablename1,tablename2 笛卡爾積 多表查詢中,如果沒有連線條件,則會產生笛卡爾積 數學中的定義 假設集合a 集合b 則兩個集合的笛卡爾積為 實際執行環境下,應避免使用笛卡爾積 解決方案 在where加入有效的連線條件 等值連線 ...

mysql多表查詢方式 MySQL多表查詢方式問題

你的 sql 沒有用到任何索引,對 a b 兩個表都是全表掃瞄,在資料量小的時候是沒有問題的,但是如果資料量超過 100 萬,效能問題就會突顯出來。這裡不清楚你的 created at 欄位是什麼型別,不過從你的 date format created at,y m d 看來,應該是 datetim...

mysql 多表查詢or MySQL 多表查詢

前期準備 建表create table dep id int,name varchar 20 create table emp id int primary key auto increment,name varchar 20 enum male female not null default ma...