我有一个Student
表,其中的列如下:
| email (PK) | name |
我有一张带有栏目的书桌:
| bookid(PK) | title |
我有一个副本表,其中包含人们拥有的图书副本
| emailofOwner(FK to student.email) | bookid(FK to book.bookid) |
学生当然可以拥有多本书。我的目的是找到只拥有1本书的学生的名字而没有其他但只有bookid = 3;
我试图让那些只拥有一本书的人。
select c.emailofOwner
from copy c
group by c.emailofOwner
having count(*) = 1 ;
答案 0 :(得分:3)
SELECT t1.name
FROM student t1
INNER JOIN
(
SELECT emailofOwner
FROM copy
GROUP BY emailofOwner
HAVING COUNT(DISTINCT bookid) = 1 AND MAX(bookid) = 3
) t2
ON t1.email = t2.emailofOwner
上述查询使用子查询来限制拥有一本且只有一本ID为3
的图书的学生。子查询与您的尝试相同,只是它添加了最大书籍ID为3
的限制。在这种情况下,由于每个保留组只有一本书,这只是检查书籍ID的值。
答案 1 :(得分:1)
仅限学生
select s.name, s.email, count(*) as numBooks
from student s, copy c
where s.email = c.emailOfOwner
group by email
having count(*) = 1
有书3的人只能预订3:
select s.name, s.email, count(*) as numBooks
from student s, copy c
where s.email = c.emailOfOwner
group by email
having count(*) = 1 and min(bookId) = 3;
查看此SQL Fiddle。