表联接 多表联接用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;