MySQL學習筆記 高階聯結(重要)

2021-10-03 21:14:52 字數 2990 閱讀 9643

select p.name as p_name,

c.name as c_name,

b.name as b_name,

price1,

model

from product as p,product_category as c,brand as b

where p.categoryid=c.id

and p.brandid=b.id

and c.id=

615432733113008653

and b.id=

-9014347894162505346

order

by p.name;

品牌表brand、商品表product、品類表product_category都被起了別名。但表別名只能在查詢執行中使用,不能返回到客戶機中(列別名可以)。

問題描述:發現商品id=-9223342254556101702的id存在錯誤,查詢該品牌的其他商品id是否存在問題。分為兩步:找到商品id=-9223342254556101702對應的品牌id,再由品牌id確定該品牌的所有商品id。即用子查詢解決。

select brandid

from product

where product.id=

-9223342254556101702

;

select  product.id,product.name

from product

where product.brandid=

4860751648763693994

;

select  product.id,product.name

from product

where product.brandid=

(select brandid

from product

where product.id=

-9223342254556101702

);

現在用聯結解決該問題:

select p1.id,p1.name

from product as p1,product as p2

where p1.brandid=p2.brandid #自聯結

and p2.id=

-9223342254556101702

;

select c.*,

p.name as p_name,

b.name as b_name,

price1,

model

from product as p,product_category as c,brand as b

where p.categoryid=c.id

and p.brandid=b.id

and c.id=

615432733113008653

and b.id=

-9014347894162505346

limit0,

5;

例:檢索所有的商品名稱和其對應品類名稱,包括沒有品類名稱的商品。此時用外部聯結。

下面是外部右聯結

select product.name as p_name,

product_category.name as c_name

from product right

outer

join product_category

on product.categoryid=product_category.id

limit0,

5;

類似內部聯結,這條select語句使用了關鍵字outer join來指定聯結的型別。但與內部聯結不同的是,外部聯結還包括沒有關聯行的行。在使用outer join語法時,必須使用right或left關鍵字指定包括其所有行的表( right指出的是outer j0in右邊的表,而left指出的是outer join左邊的表)。上面的例子使用right outer join從fron子句的右邊表(product表)中選擇所有行。如果想從左邊的表中選擇所有行,應該使用left outer join, 如下例所示:

下面是外部左聯結

select product.name as p_name,

product_category.name as c_name

from product left

outer

join product_category

on product.categoryid=product_category.id

limit0,

5;

到底用左聯結還是右聯結,哪種方便用哪種。

下面是內部聯結:包含有關聯行

select product.name as p_name,

product_category.name as c_name

from product inner

join product_category

on product.categoryid=product_category.id

limit0,

5;

例:不同品類的商品數量

select product.name as p_name,

product_category.name as c_name,

count

(product.id)

as num_product

from product inner

join product_category

on product.categoryid=product_category.id

group

by c_name;

SQL學習筆記之建立高階聯結

列別名使用方法 列的表示式 對列聚集函式 對列使用其他函式 as 列別名 表別名使用方法 在from子句中,表名 as 表別名 給表起別名有兩個優點 縮短sql語句,使得語法更簡潔 可以在select語句中多次使用相同的表 select cust name,cust contact from cus...

Mysql學習 第十三章 高階聯結

sql 除了可以對列名和計算字段使用別名,還允許給表名起別名。縮短 sql語句 允許在一條 select 語句中多次使用相同的表。select cust name,cust contact from customers as c,orders as o,orderitems as oi where ...

SQL學習之高階聯結 自聯結 自然聯結 外聯接

這是講解所需要的sql指令碼 一 自聯結 如下 select from customers 現在有個需求,需要給tom同一公司的所有會員傳送一條郵件。分析下基本思路,首先根據tom找到其所在的公司名,在根據公司名找到其公司民下的所有會員。下面是解決 select from customers whe...