不确定我正确地进行sql查询

时间:2016-01-01 13:51:34

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

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
    
  4. 这也应该是学分或course_id

    1. 查找未教授生物系提供的任何模块的所有教师
    2. 这个我甚至没有从哪里开始

2 个答案:

答案 0 :(得分:0)

您的所有查询都缺少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

答案 1 :(得分:0)

<button type="button" class="btn btn-primary btn-xs" id="shownum<?php echo $value['description'] ?>">