SELECT s.room_id,r.id,s.name,r.building_name from student s INNER JOIN room r on s.room_id=r.id;
复制代码
/lilipleft join:/pollip左连接:/p
--如a表有1,2,3,4,b表有2,3,4,5,那么查询的结果包含1,2,3,4
SELECT s.room_id,r.id,s.name,r.building_name from student s LEFT JOIN room r on s.room_id=r.id;
复制代码
/lilip左外连接:/p
--如a表有1,2,3,4,b表有2,3,4,5,那么查询的结果包含1
SELECT s.room_id,r.id,s.name,r.building_name from student s LEFT JOIN room r on s.room_id=r.id where r.building_name is null;
复制代码
/li/ol/lilipright join:/pollip右连接:/p
--如a表有1,2,3,4,b表有2,3,4,5,那么查询的结果包含2,3,4,5
SELECT s.room_id,r.id,s.name,r.building_name from student s RIGHT JOIN room r on s.room_id=r.id
复制代码
/lilip右外连接:/p
--如a表有1,2,3,4,b表有2,3,4,5,那么查询的结果包含5
SELECT s.room_id,r.id,s.name,r.building_name from student s RIGHT JOIN room r on s.room_id=r.id where s.room_id is null;
复制代码
/li/ol/lilip全连接(mysql不支持全连接)/p/lilip三个及以上的多表查询:/p
select r.*,s.`寝室人数`,e.* from room r left join (SELECT count(*) as '寝室人数',room_id as id from student GROUP BY room_id) as s on r.id=s.id RIGHT JOIN `repair` e on r.id=e.room_id
--注:直接先两表查询,然后接着两表查询的结果后面再连接表
复制代码
/lilip联表查询+子查询;/p
select r.*,s.`寝室人数` from room r left join (SELECT count(*) as '寝室人数',room_id as id from student GROUP BY room_id) as s on r.id=s.id
select room.id,`repair`.`describe`,student.`name` from student,room,`repair` WHERE student.room_id=(SELECT id FROM room WHERE number=2624) and `repair`.room_id=(SELECT id FROM room WHERE number=2624) and room.number=2624
复制代码
/lilip分组和过滤(当分组后还有条件时,可以使用having):/p
select room_id FROM student GROUP BY room_id having COUNT(*) = 2