# MySQL SQL语句编写
* [真题](https://www.kancloud.cn/ranjun940726/php_interview/596347#_2)
* [MySQL的关联update操作](https://www.kancloud.cn/ranjun940726/php_interview/596347#MySQLupdate_12)
* [延伸:MySQL的关联查询语句](https://www.kancloud.cn/ranjun940726/php_interview/596347#MySQL_23)
* [交叉连接(cross join)](https://www.kancloud.cn/ranjun940726/php_interview/596347#cross_join_33)
* [内连接(inner join)](https://www.kancloud.cn/ranjun940726/php_interview/596347#inner_join_44)
* [外连接(left join/right join)](https://www.kancloud.cn/ranjun940726/php_interview/596347#left_joinright_join_62)
* [联合查询(union/union all)](https://www.kancloud.cn/ranjun940726/php_interview/596347#unionunion_all_67)
* [全连接(full join):MySQL中不支持](https://www.kancloud.cn/ranjun940726/php_interview/596347#full_joinMySQL_77)
* [嵌套查询](https://www.kancloud.cn/ranjun940726/php_interview/596347#_85)
# 真题
有A(id,sex, par, cl, c2)、B(id,age,c1,c2)两张表,其中A.id与B.id关联,现在要求写出一条SQL语句,将B中age>50的记录的c1,c2更新到A表中统一记录中的c1,c2字段中。
~~~
update A,B set A.c1 = B.c1, A.c2=AB.c2 where A.id=B.id and B.age > 50;
# 连接
update A inner join B on A.id=B.id set A.c1 = B.c1, A.c2=AB.c2 where B.age > 50;
~~~
# MySQL的关联update操作
关联更新:
~~~
update A,B set A.c1 = B.c1, A.c2=AB.c2 where A.id=B.id
# 连接
update A inner join B on A.id=B.id set A.c1 = B.c1, A.c2=AB.c2 where ...
~~~
# 延伸:MySQL的关联查询语句
六种关联查询:
* 交叉连接(cross join)
* 内连接(inner join)
* 外连接(left join/right join)
* 联合查询(union/union all)
* 全连接(full join):MySQL中不支持
## 交叉连接(cross join)
~~~
select * from A,B(,C)
# 或者
select * from A cross join B(cross join C)
~~~
> 没有任何关联条件,结果是笛卡尔积,结果集会很大,没有意义,很少使用。
## 内连接(inner join)
~~~
select * from A,B where A.id = B.id
# 或者
select * from A inner join B on A.id = B.id
~~~
> 多表中同时符合某种条件的数据记录的集合
**分类:**
* 等值连接:on[A.id](http://a.id/)\=[B.id](http://b.id/)
* 不等值连接:on[A.id](http://a.id/)\>[B.id](http://b.id/)
* 自连接:select \* from A T1 inner join A T2 on[T1.id](http://t1.id/)\= T2.pid
> `inner join`可以缩写成`join`。
## 外连接(left join/right join)
左外连接:`left outer join`,已左表为主,先查询出左表,按照`on`后的关联条件匹配右表,没有匹配到的用NULL填充,可以简写成`left join`。
右外连接:`right outer join`,已左表为主,先查询出右表,按照`on`后的关联条件匹配左表,没有匹配到的用NULL填充,可以简写成`right join`。
## 联合查询(union/union all)
~~~
select * from A union select * from B union ...
~~~
把多个结果集集中在一起,`union`前的结果为基准,需要注意的是联合查询的列数要相等,相同的记录行会合并。
如果使用`union all`,不会合并重复的记录行。
## 全连接(full join):MySQL中不支持
MySQL实现全连接,可以使用`left join`和`union`和`right join`联合使用。
~~~
select * from A left join B on A.id =B.id union select * from A right join B on A.id = B.id
~~~
## 嵌套查询
建议使用,结果不好把控
用一条SQL语句的结果作为另外一条SQL语句的条件
~~~
select * from A where id in (select id from B)
~~~