2016-09-04 43 views
3

我有一個Student表列如下:SQL:得到一個特定的書所有者

| email (PK) | name | 

我有列的書表是這樣:

| bookid(PK) | title | 

我有一個副本表中有人擁有的圖書副本

| emailofOwner(FK to student.email) | bookid(FK to book.bookid) | 

A學生當然可以擁有多本書。我的目標是找到只擁有一本這樣的書的學生的名字,而沒有別的書,但書本= 3;

我試圖讓那些只擁有一本書的人。

select c.emailofOwner 
from copy c 
group by c.emailofOwner 
having count(*) = 1 ; 
+0

你能澄清「沒有別的書嗎= 3」嗎? –

+0

意味着學生不應該擁有書籍3和書籍4.只有書籍3 – RStyle

+0

所以你的意思是擁有書籍3和只有書籍3的學生? –

回答

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的值。

+0

如果書籍ID是'2'會怎麼樣? – Owen

+0

@Owen然後它會失敗,很明顯,因爲最大書籍ID是2,而不是3。 –

+0

糟糕,好點。 – Owen

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

相關問題