内部联结:
(1)标准的联结不设立联结条件(where语句),因为返回的结果数目是第一个表中行数×第二个表中行数,这种现象又叫笛卡儿积。
(2)内部联结设置了联结条件,只有满足了联结条件的两表对应行才会显示出来,也就是显示两表关于联结条件的交集部分,如:
SELECT * FROM table1 INNER JOIN table2 ON table1.id=table2.id
(3)使用内部联结进行多表更新的例子如下:
UPDATE tdb_goods INNER JOIN tdb_goods_cate ON tdb_goods.goods_cate = tdb_goods_cate.goods_cate SET tdb_goods.goods_cate = tdb_goods_cate.id
两张表联结显示:
SELECT * from tdb_goods INNER JOIN tdb_goods_cate ON tdb_goods.goods_cate = tdb_goods_cate.id
三张表联结显示:
SELECT * from tdb_goods INNER JOIN tdb_goods_cate ON tdb_goods.goods_cate = tdb_goods_cate.id INNER JOIN tdb_goods_brand ON tdb_goods.brand_name = tdb_goods_brand.id;
外部联结:
外部联结是在内部联结的基础上,保留了没有关联的行,也就是说左右表字段可以不满足联结关联条件,如:
左外部联结:
SELECT * FROM table1 LEFT OUTER JOIN table2 ON table1.id=table2.id
右外部联结:
SELECT * FROM table1 RIGHT OUTER JOIN table2 ON table1.id=table2.id
左联结和右联结的区别就是:左联结是左表全显示,右表显示满足联结条件的;右联结是右表全显示,左表显示满足联结条件的。
内联结和外联结图表显示:
内联结为图1,左联结为图2,右联结为图3:
自联结:
自联结是同一个数据表对自身进行联结,可用于无限分类的数据表设计(类似递归的思想),比如一个数据表如下:
其中,parent_id表示该type的父类id号。
如果想查看所有父类对应的子类表,可用如下语句:
SELECT p.type_id,p.type_name,s.type_name FROM tdb_goods_types AS p LEFT JOIN tdb_goods_types AS s ON s.parent_id = p.type_id;
如果想查看所有父类对应的子类的数目,可用如下语句:
SELECT p.type_id,p.type_name,count(s.type_name) AS child_num FROM tdb_goods_types AS p LEFT JOIN tdb_goods_types AS s ON s.parent_id = p.type_id GROUP BY p.type_name ORDER BY p.type_id;
如果想将上述查找到的父类的子类数目作为字段列,添加到这个数据表中,可做如下操作:
ALTER TABLE tdb_goods_types ADD child_num smallint default 0;
UPDATE tdb_goods_types AS t1 INNER JOIN
(SELECT p.type_id,p.type_name,count(s.type_name) AS child_num FROM tdb_goods_types AS p LEFT JOIN tdb_goods_types AS s ON s.parent_id = p.type_id group by p.type_name order by p.type_id) AS t2
ON t1.type_id = t2.type_id SET t1.child_num = t2.child_num;
得到的结果如下: