从一个表中选择在其他表中不存在三次的表

时间:2013-03-22 14:18:05

标签: mysql sql join

我有一张桌子,里面装满了学生提交的不同项目。每个项目都应由三位不同的评委来评判。所以还有另一个分数表,其中包括projectid和judgeid。我正在尝试编写一个查询,可以选择任何尚未被判断过三次的项目。

以下是一些示例表......

项目

projectid | projectname
-----------------------
9         | Kintetics
11        | Volcano
15        | Robots
22        | Oceanlife

得分

scoreid (AI) | projectid | judgeid | score
------------------------------------------
1            | 9         | 15      | 5
2            | 11        | 15      | 18
3            | 9         | 23      | 12
4            | 11        | 23      | 11
5            | 9         | 45      | 19
6            | 22        | 15      | 3

我希望这个查询返回项目11,15和22,因为这三个人还没有分配给他们三名法官。

5 个答案:

答案 0 :(得分:4)

SELECT  a.ProjectID, a.ProjectName
FROM    Projects a
        LEFT JOIN Scores b
            ON a.ProjectID = b.ProjectID
GROUP   BY a.ProjectID, a.ProjectName
HAVING  COUNT(a.ProjectID) < 3

要进一步了解联接,请访问以下链接:

输出

╔═══════════╦═════════════╗
║ PROJECTID ║ PROJECTNAME ║
╠═══════════╬═════════════╣
║        11 ║ Volcano     ║
║        15 ║ Robots      ║
║        22 ║ Oceanlife   ║
╚═══════════╩═════════════╝

答案 1 :(得分:1)

另一种选择:

SELECT  a.ProjectID, a.ProjectName
FROM    Projects a
LEFT JOIN (select ProjectID, count(*) counted from Scores) b
       ON a.ProjectID = b.ProjectID
WHERE COALESCE(b.counted,0) < 3

答案 2 :(得分:1)

SELECT COUNT(scores.id) AS score_count, projects.* 
FROM scores, projects
WHERE scores.projectid = projects.id
GROUP BY projects.id
HAVING score_count > 2

答案 3 :(得分:0)

试试这个

select * from scores where id not in (select id from scores where project id in (select projectid from scores group by projectid having count(prjectid)=3))

答案 4 :(得分:0)

试试这个:

SELECT * FROM Projects p WHERE (SELECT COUNT(*) FROM Scores s WHERE s.projectid = p.projectid) < 3