mysql表联结

来源:互联网 发布:设置防火墙允许端口 编辑:程序博客网 时间:2024/06/02 06:40

mysql 的联结 分为几种 自联结、内部联结、外部联结


内部联结:

 一般是join或者inner join 链接 需要两个表中的列满足条件 才会被返回  

例如

mysql> select a.goods_id,b.goods_commonid from club_goods a,club_goods_common b
where a.goods_commonid=b.goods_commonid;
+----------+----------------+
| goods_id | goods_commonid |
+----------+----------------+
|       38 |         100008 |
|       39 |         100008 |
|       40 |         100008 |

|       41 |         100008 |

mysql> select a.goods_id,b.goods_commonid from club_goods a inner join club_good
s_common b  on a.goods_commonid=b.goods_commonid;
+----------+----------------+
| goods_id | goods_commonid |
+----------+----------------+
|       38 |         100008 |
|       39 |         100008 |
|       40 |         100008 |
|       41 |         100008 |

两种不同的写法

自联结 就是本表的自我联结 自我链接也可以用子查询来写  具体那种看实际情况 性能  自联结可以简单的去实现那种同表子分类的情况

例如

自联结

mysql> select a.class_name as parent_name,b.class_name from test_goods_class a,
test_goods_class b where a.class_id=b.parent_id;
+-------------+------------+
| parent_name | class_name |
+-------------+------------+
| 1212        | 2321321    |
+-------------+------------+
1 row in set (0.00 sec)

子查询

mysql> select class_name from test_goods_class where class_id=(select parent_id
from test_goods_class where class_name='2321321');
+------------+
| class_name |
+------------+
| 1212       |
+------------+
1 row in set (0.00 sec)

外部联结的话  有左联结 右联结 全联结 交叉联结

左连接 是以左边表的条件为准 找出符合条件的数据 没有的话 则是空

mysql> select a.goods_name,b.class_name from test_goods a left join test_goods_c
lass b on a.class_id=b.class_id;
+------------+------------+
| goods_name | class_name |
+------------+------------+
| 商品1      | 1212       |
| 商品2      | NULL       |
+------------+------------+
2 rows in set (0.00 sec)


右联结则跟左联结相反

mysql> select a.goods_name,b.class_name from test_goods a right join test_goods_
class b on a.class_id=b.class_id;
+------------+------------+
| goods_name | class_name |
+------------+------------+
| 商品1      | 1212       |
| NULL       | 2321321    |
+------------+------------+
2 rows in set (0.00 sec)

全联结 则是 左右相加去重 貌似mysql 低版本才会有 高版本的没有

交叉联结则是 不加条件的联结 会产生笛卡尔积



原创粉丝点击