Search code examples
sqlrelational-databaserelationrelational-algebrarelational-division

Writing a query in strictly relational algebra (AS IN NOT SQL/MYSQL)


So here are three relations:

Table Members

Members(member_id, name, city, state)

where member_id is the primary key

Table Borrowed

Borrowed(borrow_id, lib_id, member_id)

where borrow_id is the primary key

Table Libraries

Libraries(lib_id, lib_address, lib_city, lib_state)

where lib_id is the primary key

Both lib_id and member_id are foreign keys

So I am trying to write a query that finds all of the member_id of members that have borrowed a book at EVERY library in their city. This means that

members.city = libraries.lib_city AND members.state = libraries.lib_state

I was thinking about using relational division. For example you have a relation consisting of the member_id's and all of the lib_id where they have borrowed a book. And you divide this by a relation that consists of all of the lib_id in that member's city.

However, I am confused as to how to write this in relational algebraic terms.

In mysql/sql it is very easy but the translation to relational algebra is where I get stuck.


Solution

  • One strategy is to match the COUNT(DISTINCT lib_id) per member_id with the total COUNT(DISTINCT lib_id) per city. If the two are equal, the individual has borrowed from every library in his city.

    I think the following will do the job:

    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