码迷,mamicode.com
首页 > 其他好文 > 详细

表联接

时间:2016-05-06 02:12:44      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:


表联接 多表联接用JOIN 关键字,
标准结构:SELECT 列1,列2 form表1 JOIN 表2 ON 表1.列 = 表2.列;
ON 可以看成WHERE子句

-- 效率很低,外层查一次,里层就要查一次
SELECT s.name ,(SELECT c.name FROM classes c WHERE s.classid = c.id)AS ‘班级‘ FROM sudent s;

-- 表联接
内联,INNER JOIN,一般省略写成JOIN
SELECT s.name,c.name FROM sudent s JOIN classes c ON s.classId = c.id;
SELECT s.name,c.name FROM sudent s INNER JOIN classes c ON s.classId = c.id;

SELECT s.* FROM sudent s WHERE s.classId = (SELECT c.id FROM classes c WHERE c.name = ‘1班‘);
SELECT s.* FROM sudent s JOIN classes c ON c.name = ‘1班‘ AND s.classId=c.id;

内联接简便写法:推荐 写JOIN ON
SELECT s.name,c.name FROM sudent s,classes c WHERE s.classid = c.id AND c.name = ‘1班‘;

 

外联接,左外联接,右外联接,
这是一种不太严谨的联接,有的数据都会查出来,不管ON是否匹配

SELECT s.*,c.id FROM sudent s RIGHT JOIN classes c ON c.name = ‘1班‘ AND s.classId=c.id;
SELECT s.*,c.id FROM sudent s RIGHT JOIN classes c ON s.classId=c.id;
SELECT s.*,c.id FROM sudent s LEFT JOIN classes c ON s.classId=c.id;

 

表联接

标签:

原文地址:http://www.cnblogs.com/chenyuanqiu2008/p/5464000.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!