Mysql多表查詢

來源:互聯網
上載者:User

標籤:分享   price   顯示   多表   har   creat   常用   代碼   mysql   

多表的查詢建立在存在外鍵的基礎上的幾張表

首先建立4張表product、order、orderitem、category,分別代表:商品表、訂單表、訂單項表、商品類別表

代碼如下:

-- 商品表create table product(    pid varchar(32) primary key,    pname varchar(100),    price double,    category_id varchar(32));-- 訂單表create table orders(    oid varchar(32) primary key,    totalprice double);-- 訂單項表create table orderitem(    oid varchar(50),    pid varchar(50));-- 分類表create table category(    cid varchar(32) primary key,    cname varchar(100));

 

分析:商品與訂單之間是多對一關聯性,商品與類別之間是多對對一關係,訂單與商品是多對多關係,我們可以通過訂單項表來實現

建立主外鍵關係的代碼如下:

alter table product add foreign key(category_id) references category(cid);-- 2個主鍵確定一個  聯合主鍵alter table orderitem add primary key(oid,pid);-- 訂單表和訂單項之間的主外鍵關係alter table orderitem add foreign key(oid) references orders(oid);-- 商品表和訂單項表的主外鍵關係alter table orderitem add foreign key(pid) references product(pid);

查詢1、交叉串連查詢(得到笛卡爾積,會很亂,也不是我們想要的結果)

select * from product,category;

查詢2、內串連查詢 (分為顯式內串連查詢和隱式內串連查詢)

-- 內串連  inner jion  inner可以省略  內串連查詢的是交集的部分    -- 顯示內串連查詢後面有on主表的主鍵與從表的外鍵關係select * from category inner join product on cid=category_id-- 隱式內串連    查詢結果一樣的  常用select * from category c,product p where c.cid=p.category_id;

得到的結果是當category表與product表的交集部分

查詢3、外串連查詢(分為左外串連和右外串連查詢)

-- 外串連查詢分為左外串連與右外串連    -- 左外串連select * from category left join product on cid=category_id;    -- 右外串連select * from category right join product on cid=category_id;

左外串連和右外串連的區別如

 

  子查詢:使用一個sql查詢的結果作為另外一個sql查詢的條件,如下所示

select * from product where category_id=(select cid from category where cname=‘化妝品‘);

 

Mysql多表查詢

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.