您的位置:首页 > 数据库

sql语句连接查询.

2017-07-14 20:45 288 查看
sql语句连接查询.
接触sql语句这么长时间了,牵涉到连接的时候,总是google别人的.

 
今天好好学学sql 的连接查询

 
准备工作 :

mysql5.6 建表语句



查询语句

select p.id_p,p.firstName,p.lastName,o.id_o,o.orderno from persons p,orders o where p.id_p=o.id_o;



再多表查询也一样 在from table1 alias1 ,table2 alias2,table3 alias3 wher 条件;

 

 

 
w3c讲的太浅, 换博客了,重新建表







  关联查询:
1. 内连接:在每个表中找出符合条件的共有记录。[x inner join y on...]
第一种写法:(只使用where)
select t.teacher_name, s.student_name from teacher t,student s where t.id = s.teacher_id;
第二种写法:(join .. on.. )
select t.teacher_name, s.student_name from teacher t join student s on t.id = s.teacher_id;
第三种写法:(inner join .. on.. )
select t.teacher_name, s.student_name from teacher t inner join student s on t.id = s.teacher_id;



 2. 外连接
外连接有三种方式:左连接,右连接和全连接。
2.1 左连接:根据左表的记录,在被连接的右表中找出符合条件的记录与之匹配,如果找不到与左表匹配的,用null表示。[x left [outer] join y on...
第一种写法:(left join .. on ..)
select t.teacher_name, s.student_name from teacher t left join student s on t.id = s.teacher_id;
第二种写法:(left outer join .. on ..)
select t.teacher_name, s.student_name from teacher t left outer join student s on t.id = s.teacher_id;
第三种写法:"(+)" 所在位置的另一侧为连接的方向(本例中teacher连接)
有些数据库不支持 mysql不支持
select t.teacher_name, s.student_name from teacher t, student s where t.id = s.teacher_id(+);

 
 2.2 右连接:
根据右表的记录(以右表为基准),在被连接的左表中找出符合条件的记录与之匹配,如果找不到匹配的,用null填充。[x right [outer] join y on...]
第一种写法:()
select t.teacher_name, s.student_name from teacher t right join student s on t.id = s.teacher_id;
第二种写法:
select t.teacher_name, s.student_name from teacher t right outer join student s on t.id = s.teacher_id;
第三种写法:"(+)" 所在位置的另一侧为连接的方向
select t.teacher_name, s.student_name from teacher t, student s where t.id(+) = s.teacher_id;

 
2.3 全连接:
返回符合条件的所有表的记录,没有与之匹配的,用null表示(结果是左连接和右连接的并集) mysql不支持全连接
第一种写法:(full join .. on ..)
select t.teacher_name, s.student_name from teacher t full join student s on t.id = s.teacher_id;
第二种写法:(full outer join .. on)
select t.teacher_name, s.student_name from teacher t full outer join student s on t.id = s.teacher_id;
3. 自连接
自连接,连接的两个表都是同一个表,同样可以由内连接,外连接各种组合方式,按实际应用去组合。
SELECT a.*, b.* FROM table_1 a,table_1 b WHERE a.[name] = b.[name]  与内连接第一种方式相同

 
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: