1.

image.png

  1. select name
  2. from teacher
  3. where dept is null

2.

image.png

  1. SELECT teacher.name, dept.name
  2. FROM teacher INNER JOIN dept
  3. ON (teacher.dept=dept.id)

3.

image.png

  1. SELECT teacher.name,dept.name
  2. FROM teacher
  3. LEFT JOIN dept ON teacher.dept = dept.id

笔记:左查询(LEFT JOIN)将左边表的主键全部保留;右查询反之;INNER JOIN 则仅保留相同的连接项

4.

查询所有部门的教师名称
image.png

  1. select teacher.name,dept.name
  2. from dept
  3. left join teacher on teacher.dept = dept.id

5.

image.png

  1. select name,coalesce(mobile,'07986 444 2266' )
  2. from teacher

6.image.png

  1. select x.name,coalesce(y.name,'None')
  2. from teacher as x
  3. left join dept as y on x.dept = y.id

7.

image.png

  1. select count(name),count(mobile)
  2. from teacher

8.

image.png

  1. select dept.name,count(teacher.name)
  2. from teacher
  3. right join dept on teacher.dept = dept.id
  4. group by dept.name

9.

image.png

  1. select
  2. teacher.name,
  3. case
  4. when dept.id in (1,2) then 'Sci'
  5. else 'Art'
  6. end
  7. from teacher
  8. left join dept on teacher.dept = dept.id

10.

image.png

  1. select
  2. teacher.name,
  3. case
  4. when teacher.dept in (1,2) then 'Sci'
  5. when teacher.dept = 3 then 'Art'
  6. else 'None'
  7. end
  8. from teacher
  9. left join dept on teacher.dept = dept.id