MySQL连接查询常见坑1

由于MySQL不是编译器,SQL语句也不是用于开发程序的编程语言,报错机制不完善,所以其非常不 灵活,错误也不易找到,因此也随之带来了一些坑,例如在连接查询中:

查询所有同学的学生编号、学生姓名、选课总数、所有课程的总成绩(没成绩的显示为 null):


```sql
select sid,sname from student as  tmp left join (
    select sid,count(*) as totalCourse, sum(score) as totalScore from sc group by sid
  ) as temp on tmp.sid=temp.sid;

会报错:Error Code: 1052. Column ‘sid’ in field list is ambiguous
为什么呢?
因为我原本以为是先 (select sid,sname from student),然后命名这张表是tmp,然后执行左连 接,但实际上,MySQL执行顺序并非如此,它会先执行 student as tmp把学生表命名为tmp,然后执行:

```sql
left join (
    select sid,count(*) as totalCourse, sum(score) as totalScore from sc group by sid
  ) as temp on tmp.sid=temp.sid;

注意,left join后的表,看起来只有一个sid字段,实际上有两个,只不过多余的被隐藏了,所以这时 执行最开始的select sid,sname from 这张左连接之后的表时,MySQL不知道要选取哪个sid字段,于 是报错
如果把开始的select语句改为:select temp.sid,sname,能正确求解吗?
能执行,但只会显示 sid、sname属性,没有选课总数和总成绩,因为刚讲了,开头的select语句,是 在left join之后的表中查询,如果不select 选课总数和总成绩,结果中自然不会显示。
正确答案:

  select student.sid,sname, totalCourse,totalScore from student left join (
      select sid,count(*) as totalCourse, sum(score) as totalScore from sc group by sid
  )as temp on student.sid=temp.sid;

你可能感兴趣的:(MySQL,mysql,数据库,sql)