我正在尝试使用MySQL为库数据库编写SQL查询。
有两个表shelf(studentnumber, booknumber)
和booklist(booknumber,booktitle,language)
。书单表条目中有4种不同的语言,即italian, spanish, hungarian, german
。
我想了解已阅读所选语言所有图书的studentnumbers
。
表格的示例数据:
create table shelf(studentnumber INT, booknumber INT);
INSERT INTO shelf values(1,1),(1,2),(1,3),(2,1),(2,3)(2,4),(2,5),
(2,6),(3,6),(3,7)(3,8),(3,9);
create table booklist(booknumber INT, booktitle VARCHAR(50), language VARCHAR(10);
INSERT INTO booklist values(1, 'FirstBook', 'italian'),(2,'SecondBook', 'spanish'),
(3,'ThirdBook','italian'),(4,'FourthBook','german'),(5,'FifthBook','german'),
(6, 'SixthBook','spanish'),(7,'SeventhBook','hungarian'),(8,'EightBook','hungarian'),
(9,'NinthBook','hungarian'),(10,'TenthBook','Spanish'),(11,'EleventhBook', 'italian');
示例输出: 当您查看书架和书单表时,您会看到有2号学生的学生阅读所有德语书籍,而有学生3号的学生阅读所有匈牙利语书籍。 但是没有学生读过意大利语或西班牙语的所有书籍。
代码的最后一部分将如下所示,但我无法构建第一部分,可能包括NOT EXISTS
SELECT booknumber FROM booklist WHERE language ='italian';
答案 0 :(得分:0)
这应该很适合你:
select studentnumber
from shelf s1 join booklist b1 on s1.booknumber=b1.booknumber
group by studentNumber, language
having count(language) >= (
select count(*) from booklist b2
where b1.language=b2.language
group by b2.language)
输出:
2
3
您还可以添加第一个选择语句语言和计数(*),它将为您提供更多信息(他们已阅读的语言以及书籍数量),即
select studentnumber,language,count(*)
//rest of code
输出
2, german, 2
3, hungarian, 3
<强>更新强>
要显示所有以指定语言阅读书籍的学生(如评论中所要求的),只需添加WHERE子句:
select studentnumber
from shelf s1 join booklist b1 on s1.booknumber=b1.booknumber
where language='german'
group by studentNumber, language
having count(language) >= (
select count(*) from booklist b2
where b1.language=b2.language
group by b2.language)
输出:
2