【问题标题】:Not sure im doing sql queries correctly不确定我是否正确执行 sql 查询
【发布时间】:2016-01-01 13:51:33
【问题描述】:
department(dept_name, building, budget)

course(course_id, title, dept_name, credits)

instructor(ID, name, dept_name, salary)

section(course_id, sec_id, semester, year, building, room_number, time_slot_id)

teaches(ID, course_id, sec_id, semester, year)

student(ID, name, dept_name, tot_cred)

takes(ID, course_id, sec_id, semester, year, grade)
  1. 查找超过 50 名学生参加的每门课程的课程名称、学期和年份

    select course.title , takes.semester , takes.year
    from course
    natural join takes
    where course.course_id = takes.course_id
    having count(distinct ID) > 50
    
  2. 查找包含多个部分的每门课程的标题

    select title 
    from course
    natural join section 
    where course.course_id = section.course_id
    having count(distinct sec_id) > 1
    
  3. 查找在 Comp 中教授超过 5 门课程的所有讲师的 ID。科学。部门

    select ID
    from instructor
    natural join course
    where course.dept_name = instructor. dept_name
    having count(credits)>5
    

这也应该是学分或 course_id

  1. 查找所有未教授生物系提供的任何模块的教师

这个我什至不知道从哪里开始

【问题讨论】:

  • 不要使用自然连接(它依赖于隐式字段名称)。也不能有没有 group by 的有子句..
  • MySQL 还是 SQL-Server?它们不一样,甚至不相关。
  • @amdixon 我认为 MySQL 允许 HAVING 没有 GROUP BY。但他需要 GROUP BY 来处理这些查询,因为他想在组内计数。
  • 正确,在这种情况下他需要一个 group by 但 mysql 在语法上允许它

标签: mysql sql sql-server database natural-join


【解决方案1】:

您的所有查询都缺少GROUP BY 子句。

如果您使用NATURAL JOIN,则不需要WHERE 子句来关联表——NATURAL JOIN 会自动执行此操作。

select course.title , takes.semester , takes.year
from course
natural join takes
GROUP BY course.title, takes.semester, takes.year    
having count(distinct ID) > 50

select title 
from course
natural join section 
GROUP BY title
having count(distinct sec_id) > 1

select ID
from instructor
natural join course
GROUP BY ID
having count(credits)>5

您的最后一个查询还有其他几个问题。您没有使用 teaches 表将讲师链接到课程,也没有检查课程是否在 Comp 中。科学。部门。

SELECT i.id
FROM instructor AS i
JOIN teaches AS t ON i.id = t.sec_id
JOIN course AS c ON t.course_id = c.id
WHERE c.dept_name = "Comp. Sci."
HAVING COUNT(*) > 5

【讨论】:

    【解决方案2】:
    select count(t.id), c.title , t.semester , t.year
    from course c
    left join takes t on t.cource_id=c.cource_id
    group by 2,3,4
    having count(t.id) > 50
    
    select c.title, count(s.sec_id) 
    from course c
    left join section  s on c.course_id = s.course_id
    group by 1
    having count(s.sec_id) > 1
    
    select i.ID, count(c.id)
    from instructor i
    left join course c on c.dept_name = i. dept_name
    group by 1
    having count(c.id)>5
    
    select i.ID
    from instructor i
    left join department d on d.dept_name=i.dept_name
    where d.dept_name<>'Biology'
    

    【讨论】:

      猜你喜欢
      • 2019-05-10
      • 2015-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多