teacher表:
id | dept | name | phone | mobile |
---|---|---|---|---|
101 | 1 | Shrivell | 2753 | 07986 555 1234 |
102 | 1 | Throd | 2754 | 07122 555 1920 |
103 | 1 | Splint | 2293 | |
104 | Spiregrain | 3287 | ||
105 | 2 | Cutflower | 3212 | 07996 555 6574 |
106 | Deadyawn | 3345 |
dept表:
id | name |
---|---|
1 | Computing |
2 | Design |
3 | Engineering |
1.List the teachers who have NULL for their department.
select name from teacher where dept is NULL;
2.Note the INNER JOIN misses the teachers with no department and the departments with no teacher.
SELECT teacher.name, dept.name FROM teacher INNER JOIN dept ON teacher.dept=dept.id;
内部联结INNER JOIN…ON 和之前的 JOIN…ON 是一样的。内部联结对NULL值不起作用。若对应的那一列有NULL值,则这些行无法对应到另一个表。只有有值的那些行能和另一表对应,才能被选择。
所谓NULL值,就是有些行不是两个表都有的,有些这个有,另一个没有。
3.Use a different JOIN so that all teachers are listed.
select t.name,d.name from teacher t left join dept d on t.dept=d.id;
解题思路: left join,以teacher左表为主表,向左连接。和inner join的区别在于,inner join公共列出现null值时,将忽略null值。
4.Use a different JOIN so that all departments are listed.
select t.name,d.name from teacher t right join dept d on t.dept=d.id;
解题思路,right join,以dept右表为主表,向右连接。
Using Coalesce Fuction
5.Use COALESCE to print the mobile number. Use the number \'07986 444 2266\' if there is no number given. Show teacher name and mobile number or \'07986 444 2266\'
使用coalesce函数,显示教师姓名和电话号码,如果电话号码是空值,用‘07986 444 2266’填充
select name,coalesce(mobile,\'07986 444 2266\') from teacher;
解题思路,colaesce函数是缺失值处理,针对的是null的情况,注意,coalesce函数对空格不起作用。
6.Use the COALESCE function and a LEFT JOIN to print the teacher name and department name. Use the string \'None\' where there is no department.
select t.name,coalesce(d.name,\'None\') from teacher t left join dept d on t.dept=d.id;
7.Use COUNT to show the number of teachers and the number of mobile phones.
select count(name),count(mobile) from teacher;
8.Use COUNT and GROUP BY dept.name to show each department and the number of staff. Use a RIGHT JOIN to ensure that the Engineering department is listed.
select d.name,count(t.name) from teacher t right join dept d on t.dept=d.id group by 1;
9.Use CASE to show the name of each teacher followed by \'Sci\' if the teacher is in dept 1 or 2 and \'Art\' otherwise.
使用 CASE 显示每位教师的姓名,如果教师在部门 1 或 2,则显示“Sci”,否则显示“Art”。
select name,(case when dept in(1,2) then \'Sci\' else \'Art\' end) from teacher;
解题思路:考察case when
10.Use CASE to show the name of each teacher followed by \'Sci\' if the teacher is in dept 1 or 2, show \'Art\' if the teacher\'s dept is 3 and \'None\' otherwise.
使用 CASE 显示每位教师的姓名,如果教师在部门 1 或 2,则显示“Sci”,如果教师的部门是 3,则显示“Art”,否则显示“None”。
select name,(case when dept in(1,2) then \'Sci\' when dept=3 then \'Art\' else \'None\' end) from teacher;
解题思路:考察case when 多个条件。
来源:https://www.cnblogs.com/ruoli-121288/p/16310507.html
本站部分图文来源于网络,如有侵权请联系删除。