mysql表關聯 MySQL表關聯的幾種常用方式

2021-10-18 11:56:47 字數 2669 閱讀 9927

工作中我們經常會使用表與表關聯來查詢資料,如果對join 不熟悉,可能會得到我們不想要的節過,這裡就來介紹下join的幾種常用方法:

建表及插入資料,

create table school (

sch_id int(11) not null auto_increment,

sch_name varchar(50) not null,

sch_addr varchar(100) default null,

primary key (sch_id)

) engine=innodb auto_increment=9 default charset=utf8;

create table student (

st_id int(11) not null auto_increment,

st_name varchar(20) not null,

age smallint(6) default null,

hight int(5) default null,

sch_id int(11) default null,

primary key (st_id),

key sch_id (sch_id)

) engine=innodb auto_increment=10 default charset=utf8 ;

insert into school values (1,'南開大學','南開'),(2,'**財經大學','北京'),(3,'香港理工大學','香港'),(4,'西安交通大學','西安'),(5,'雪梨大學','雪梨'),(6,'曼徹斯特大學','曼徹斯特'),(8,'延安抗日軍政大學','延安');

insert into student values (1,'王曉陽',26,168,6),(2,'王楠',28,162,2),(3,'楊振宇',30,178,1),(4,'苗昕',28,162,3),(5,'張詩雨',27,171,5),(8,'李倩',28,162,4),(9,'蔣結石',26,178,7);

1.左關聯:以左表為中心,查出左表的全部資料,關聯字段值不相等則右表查出的資料顯示為空;

2.右關聯:以右表為中心,查出右表的全部資料,關聯字段值不相等則左表查出的資料顯示為空;

3.內關聯:查出兩表關聯字段等值的資料

4.查出只屬於左表的資料

5.查出只屬於右表的資料

6.查出全部資料

select * from school a left join student b on a.sch_id=b.sch_id union select *from school a right join student b on a.sch_id=b.sch_id;

7.查出左表和右表關聯不相等的資料

select * from school a left join student b on a.sch_id=b.sch_id where b.st_id is null union select *from school a right join student b on a.sch_id=b.sch_id where a.sch_id is null;

MySQL關聯表查詢資料

資料庫中有兩張表 t1表如下 t2表如下 inner join只有左右表的資料匹配才會返回。select from t1 inner join t2 on t1.cid t2.id 結果如下 left join返回聯接左邊表的所有行,即使在右邊表中沒有匹配的行。select from t1 left...

MySQL 表的關聯join

目錄 1 left join 2 right join 3 inner join 4 full outer join oracle mysql通過join實現表的關聯,關聯方式主要有三種。有兩個表用於下面的測試 select from test select from test2 結果分別為 lef...

mysql三表關聯加索引 mysql 三表索引優化

建表語句 create table if not exists phone phoneid int 10 unsigned not null auto increment,card int 10 unsigned not null,primary key phoneid engine innodb ...