设为首页 加入收藏

TOP

Mysql重新整理笔记--woods备忘(四)
2015-11-21 02:02:03 来源: 作者: 【 】 浏览:1
Tags:Mysql 重新 整理 笔记 --woods 备忘
----+ | 1 | aaa | 1 | | 2 | bbb | 2 | | 3 | bbb | 4 | +----+------+-------+ mysql> select * from tb; +----+------+ | id | name | +----+------+ | 1 | xxx | | 2 | yyy | | 3 | yyy | +----+------+

?

?
1.笛卡尔积查询:两张表中一条一条对应的记录,m条记录和n条记录查询,最后得到m*n条记录,其中很多错误数据
select * from ta ,tb;

mysql> select * from ta ,tb;
 +----+------+-------+----+------+
 | id | name | tb_id | id | name |
 +----+------+-------+----+------+
 |  1 | aaa  |  1 |  1 | xxx  |
 |  2 | bbb  |  2 |  1 | xxx  |
 |  3 | bbb  |  4 |  1 | xxx  |
 |  1 | aaa  |  1 |  2 | yyy  |
 |  2 | bbb  |  2 |  2 | yyy  |
 |  3 | bbb  |  4 |  2 | yyy  |
 |  1 | aaa  |  1 |  3 | yyy  |
 |  2 | bbb  |  2 |  3 | yyy  |
 |  3 | bbb  |  4 |  3 | yyy  |
 +----+------+-------+----+------+

?

?
2.内连接:查询两张表中都有的关联数据,相当于利用条件从笛卡尔积结果中筛选出了正确的结果。
select * from ta ,tb where ta.tb_id = tb.id;
select * from ta inner join tb on ta.tb_id = tb.id;

mysql> select * from ta inner join tb on ta.tb_id = tb.id;
 +----+------+-------+----+------+
 | id | name | tb_id | id | name |
 +----+------+-------+----+------+
 |  1 | aaa  |  1 |  1 | xxx  |
 |  2 | bbb  |  2 |  2 | yyy  |
 +----+------+-------+----+------+

?

?
3.外连接
?
(1)左外连接:在内连接的基础上增加左边有右边没有的结果
select * from ta left join tb on ta.tb_id = tb.id;

mysql> select * from ta left join tb on ta.tb_id = tb.id;
 +----+------+-------+------+------+
 | id | name | tb_id | id| name |
 +----+------+-------+------+------+
 |  1 | aaa  |  1 | 1 | xxx  |
 |  2 | bbb  |  2 | 2 | yyy  |
 |  3 | bbb  |  4 | NULL | NULL |
 +----+------+-------+------+------+

?

?
(2)右外连接:在内连接的基础上增加右边有左边没有的结果
 select * from ta right join tb on ta.tb_id = tb.id;

 mysql> select * from ta right join tb on ta.tb_id = tb.id;
 +------+------+-------+----+------+
 | id| name | tb_id | id | name |
 +------+------+-------+----+------+
 | 1 | aaa  |  1 |  1 | xxx  |
 | 2 | bbb  |  2 |  2 | yyy  |
 | NULL | NULL |  NULL |  3 | yyy  |
 +------+------+-------+----+------+

?

?
(3)全外连接:在内连接的基础上增加左边有右边没有的和右边有左边没有的结果
 select * from ta full join tb on ta.tb_id = tb.id; --mysql不支持全外连接
 select * from ta left join tb on ta.tb_id = tb.id
 union
 select * from ta right join tb on ta.tb_id = tb.id;

 mysql> select * from ta left join tb on ta.tb_id = tb.id
  -> union
  -> select * from ta right join tb on ta.tb_id = tb.id; --mysql可以使用此种方式间接实现全外连接
 +------+------+-------+------+------+
 | id| name | tb_id | id| name |
 +------+------+-------+------+------+
 | 1 | aaa  |  1 | 1 | xxx  |
 | 2 | bbb  |  2 | 2 | yyy  |
 | 3 | bbb  |  4 | NULL | NULL |
 | NULL | NULL |  NULL | 3 | yyy  |
 +------+------+-------+------+------+

?


首页 上一页 1 2 3 4 下一页 尾页 4/4/4
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇辛星浅析MySQL中的last_insert_id.. 下一篇MySQL转换Oracle的注意事项

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: