Loading... # 引言 想写这个想了好久,始终没有时间来做,最近抽出了点时间来搞这个。 # 普通查询 subject 也是关键字 所以创建表以及引用时使用`字符来括起来 下面是一张表,简单的学生表 <div class="tip inlineBlock share"> 学生表-student | id | name| age | | --- | --- | --- | | 1 | 张三 | 3 | | 2 | 李四 | 4 | | 3 | 王五 | 5 | </div> 下面是一张表,学生的成绩表 <div class="tip inlineBlock share"> 成绩表-score | id | sid | score| subject| | -- | --- | --- | --- | | 1 | 1 | 80 | 语文 | | 2 | 1 | 90 | 数学 | | 3 | 2 | 85 | 语文 | | 4 | 2 | 95 | 数学 | </div> ## 查询学号为1的学生 ```sql SELECT * FROM student WHERE id = 1 ``` ## 查询学号为1的学生的姓名 ```sql SELECT name FROM student WHERE id = 1 ``` ## 查询学号为1和2的学生的姓名 ```sql SELECT * FROM student WHERE id IN (1,2) ``` ## 查询学号为1和2的学生的姓名 ```sql SELECT * FROM student WHERE id IN (1,2) ``` ## 查询学生张三的语文成绩 ```SQL SELECT SCORE FROM student s LEFT JOIN score sc ON s.id = sc.sid WHERE s.name = '张三' ``` ## 查询学生张三的语文成绩 ```SQL SELECT SCORE FROM student s LEFT JOIN score sc ON s.id = sc.sid WHERE s.name = '张三' and sc.subject = '语文' ``` ## 查询各科成绩总和 ```sql # 这里的subject用``阔了起来 SELECT SUM(score),sc.`subject` FROM score sc LEFT JOIN student s ON s.id = sc.sid GROUP BY sc.subject ``` <div class="tip inlineBlock info"> 以上已经包括了大多数常用查询,还能想出什么花样?可以评论 </div> # 多表查询的JOIN ## LEFT /INNER /RIGHT JOIN 分别什么意思? 比如说两张表,表A和表B,如下表格吧 表A | id| c1 | c2 | | --- | --- | --- | | 1 | a | b | | 2 | c | d | 表B | id| c3 | c4 | | --- | --- | --- | | 1 | a | b | | 2 | c | d | | 3 | e | f | ### LEFT 如果表A LEFT JOIN 表B 根据ID相等作为条件 即`select * from t1 left join t2 ON t1.id = t2.id` 结果是 |id| c1 |c2| id(1)| c3| c4| | --- | --- | --- | --- | --- | --- | |1 |a |b |1 |a |b| |2 |c |d |2 |c |d| ### INNER 如果表A INNER JOIN 表B 根据ID相等作为条件 即`select * from t1 inner join t2 ON t1.id = t2.id` 结果是 |id| c1 |c2| id(1)| c3| c4| | --- | --- | --- | --- | --- | --- | |1 |a |b |1 |a |b| |2 |c |d |2 |c |d| 我们发现上面两个结果一样,如果此时表A中id为1的记录删除了,结果会是这样的 |id| c1 |c2| id(1)| c3| c4| | --- | --- | --- | --- | --- | --- | |2 |c |d |2 |c |d| ### RIGHT 如果表A RIGHT JOIN 表B 根据ID相等作为条件 即`select * from t1 right join t2 ON t1.id = t2.id` |id|c1|c2|id(1)|c3|c4| | --- | --- | --- | --- | --- | --- | |1 |a |b |1 |a |b| |2 |c |d |2 |c |d| | | | |3 |e |f| 右侧表有 左侧表没有 那就留空,也就是以右表为主,LEFT INNER RIGHT 结合起来的话,更好理解了。 未完待续... © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 如果觉得我的文章对你有用,请随意赞赏