英文:
How to extract parts from a composite key?
问题
我想要获取具有评分为5的允许重复的书名列表。举例来说,如果书籍“A”有三次评分为10的评价,那么它的书名“A”应该在列表中出现三次。
我的想法是从评分的主键“(uid,isbn)”中提取“isbn”,然后选择相应的书名。因此,我编写了以下代码来选择所有的“(uid,isbn)”元组:
select (uid,isbn)
from rating
where rating = 10
然而,我不知道如何从这里访问isbn部分。你能告诉我如何做到这一点吗?
英文:
I have the following SQL tables which describe a relation where users can rate books:
CREATE TABLE Users
(
UID INT PRIMARY KEY,
Username VARCHAR(256),
DoB DATE,
Age INT,
);
CREATE TABLE Book
(
ISBN VARCHAR(17) PRIMARY KEY,
Title VARCHAR(256),
Published DATE,
Pages INT,
Language VARCHAR(256)
);
CREATE TABLE Rating
(
UID INT REFERENCES Users (UID),
ISBN VARCHAR(17) REFERENCES Book (ISBN),
PRIMARY KEY (UID,ISBN),
Rating INT
)
I want to get a list of book-titles with a rating of 5 that ALLOWS REPETITIONS for every rating. For example, if Book "A" has three ratings of 10, then its tile "A" should be in the list three times.
My idea is to extract the "isbn" from the primary key "(uid,isbn)" from rating and then select the respective titles. So I wrote the code that selects all "(uid,isbn)" tuples:
select (uid,isbn)
from rating
where rating = 10
However, I do not know how to access the isbn part from there. Could you please tell me how to do this?
答案1
得分: 2
不需要提取复合键的部分,因为它们作为单独的列存在,已经可以独立获得。例如:
SELECT
Book.Title, Rating.UID, Users.Username, Rating.ISBN, Rating.Rating
FROM Book
JOIN Rating ON Book.ISBN = Rating.ISBN
JOIN Users ON Rating.UID = Users.UID
WHERE Rating.Rating = 5
ORDER BY
Book.Title
;
Title | UID | Username | ISBN | Rating |
---|---|---|---|---|
1984 | 1 | Alice | 9780141187761 | 5 |
1984 | 3 | Charlie | 9780141187761 | 5 |
The Catcher in the Rye | 2 | Bob | 9783161484100 | 5 |
The Lord of the Rings | 1 | Alice | 9780547928227 | 5 |
The Lord of the Rings | 2 | Bob | 9780547928227 | 5 |
The Lord of the Rings | 3 | Charlie | 9780547928227 | 5 |
The Lord of the Rings | 4 | David | 9780547928227 | 5 |
To Kill a Mockingbird | 1 | Alice | 9780061120084 | 5 |
To Kill a Mockingbird | 3 | Charlie | 9780061120084 | 5 |
英文:
You do not need to extract parts of the composite key, because they exist as separate columns and hence already available independently. e.g.
SELECT
Book.Title, Rating.UID, Users.Username, Rating.ISBN, Rating.Rating
FROM Book
JOIN Rating ON Book.ISBN = Rating.ISBN
JOIN Users On Rating.UID = Users.UID
WHERE Rating.Rating = 5
ORDER BY
Book.Title
;
Title | UID | Username | ISBN | Rating |
---|---|---|---|---|
1984 | 1 | Alice | 9780141187761 | 5 |
1984 | 3 | Charlie | 9780141187761 | 5 |
The Catcher in the Rye | 2 | Bob | 9783161484100 | 5 |
The Lord of the Rings | 1 | Alice | 9780547928227 | 5 |
The Lord of the Rings | 2 | Bob | 9780547928227 | 5 |
The Lord of the Rings | 3 | Charlie | 9780547928227 | 5 |
The Lord of the Rings | 4 | David | 9780547928227 | 5 |
To Kill a Mockingbird | 1 | Alice | 9780061120084 | 5 |
To Kill a Mockingbird | 3 | Charlie | 9780061120084 | 5 |
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论