问题
tldr; Which of the three below can you not write in RA?
Our prof asked us to write 3 SQL queries. He then asked us which of them could not be written in Relation Algebra. They are as follows:
Given the following 3 tables:
Students (sID, sName); (Primary Key sID)
Courses (cID, cName); (Primary Key cID)
Enrolled (sID, cID, sectID, grade) (Primary Key sID, cID)
where foreign key (sID) references Students,
foreign key (cID) references Courses.
- Find the largest student ID.
- Get a class list (consisting of 〈sID, sName〉) for COMP 4380, and arrange the records in the list in alphabetical order of sName. (He just wants all the students who have ever taken the course).
- Count the number of students enrolled in each course (identified by course ID).
So we have:
- A query involving finding the maximum in a column of integers.
- A query involving sorting the result in alphabetical order.
- A query involving counting multiple groups.
I've managed to write an RA statement for #1 (Details here) so I know that is not it. I'm not sure about 2 and 3 however. How could you sort with the RA operations? How could you count multiple groups? I would guess 3 is possible since RA can be extended to have count as an aggregate function.
Here are the SQL statements I came up with to answer my prof's original question:
SELECT max(sID)
FROM Students
SELECT sID, sName
FROM Enrolled INNER JOIN Students
WHERE cID="COMP 4380"
ORDER BY sName
SELECT count(sID), cID
FROM Enrolled
GROUP BY cID
I haven't been able to write 2 and 3 in RA.
回答1:
Only 1 is possible in standard RA. We cannot sort, and we cannot count an arbitrary number in standard RA.
来源:https://stackoverflow.com/questions/14613953/which-of-the-following-can-you-not-do-in-relational-algebra