操作 | 描述 |
inner join | 如果表中至少有一个匹配,就返回行 |
left join | 会从左表中返回所有的值,即使右表中没有匹配 |
right join? | 会从右表中返回所有的值,即使左表中没有匹配 |
语法:join? ?(连接的表)on(判断的条件)? ?
? ? ? ? ? -- where 等值查询
? ? ? ? ? --on? ?连接查询????????
代码案例:
-- 联表查询
-- inner join
SELECT s.studentno,studentname,subjectno,studentresult
FROM student AS s
INNER JOIN result AS r
WHERE s.studentno = r.studentno
-- right join
SELECT s.studentno,studentname,subjectno,studentresult
FROM student AS s
RIGHT JOIN result AS r
ON s.studentno = r.studentno
-- left join
SELECT s.studentno,studentname,subjectno,studentresult
FROM student AS s
LEFT JOIN result AS r
ON s.studentno = r.studentno
多表查询:
1.我要查询哪些数据select……
2.从哪几个表中查,from 表? ?xxx? ?join? ? 连接的表? ? ? on? ? ? 交叉条件
3.假设存在一种多张表查询,慢慢来先查询两张表,然后再慢慢增加表
代码案例:
-- 查询缺考的同学
SELECT s.studentno,studentname,subjectno,studentresult
FROM student AS s
LEFT JOIN result AS r
ON s.studentno = r.studentno
WHERE `studentresult`IS NULL
-- 多表查询
SELECT s.`studentno`,`studentname`,`subjectname`,`studentresult`
FROM student s
RIGHT JOIN `result` r
ON s.`studentno`=r.`studentno`
INNER JOIN `subject` sub
ON r.`studentno`=sub.`subjectno`