所以这里有三个关系:
表会员
成员(member_id,姓名,城市,州)
其中member_id是主键
借阅表
借用(borrow_id,lib_id,member_id)
其中borrow_id是主键
表库
库(lib_id,lib_address,lib_city,lib_state)
其中lib_id是主键
lib_id和member_id都是外键
所以我正在尝试编写一个查询,找到在他们所在城市的每个图书馆借书的所有成员的member_id。这意味着
members.city = libraries.lib_city AND members.state = libraries.lib_state
我在考虑使用关系划分。例如,您有一个由member_id和他们借用书籍的所有lib_id组成的关系。并且你将它除以一个由该成员城市中所有lib_id组成的关系。
然而,我很困惑如何用关系代数术语来写这个。
在mysql / sql中它非常简单但是关系代数的翻译就是我被卡住的地方。
答案 0 :(得分:0)
一种策略是将每COUNT(DISTINCT lib_id)
member_id
与每个城市的总COUNT(DISTINCT lib_id)
相匹配。如果两者相等,则该人从他所在城市的每个图书馆借来。
我认为以下将完成这项工作:
SELECT
member_id,
/* Total libraries borrowed from by member */
COUNT(DISTINCT Borrowed.lib_id) AS num_libs_borrowed,
/* Total libs in the member's city */
COUNT(DISTINCT Libraries.lib_id) AS total_city_libs
FROM
Members
/* JOIN the city between Members & Libraries */
JOIN Libraries ON Members.city = Libraries.lib_city
/* JOIN member to borrowed */
JOIN Borrowed ON Members.member_id = Borrowed.member_id
GROUP BY member_id
/* If the number of libs borrowed from = the total libs in the city... */
HAVING num_libs_borrowed = total_city_libs