Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregate function in Tuple Relational Calculus

Tags:

sql

database

How do you translate a COUNT or a GROUP BY or any other aggregate function you find in SQL into TRC, i can't find any way on internet.

So I have a table User

    +----+----------+--+
    |    |   User   |  |
    +----+----------+--+
    | pk | email    |  |
    |    | password |  |
    |    | ...      |  |
    +----+----------+--+

And a table frienship

+----+-------------+--+
|    | FriendShip  |  |
+----+-------------+--+
| pk | user1_email |  |
| pk | user2_email |  |
|    | date        |  |
|    | accepted    |  |
+----+-------------+--+

And the following query in SQL:

SELECT * 
FROM user u 
LEFT OUTER JOIN friendship f ON (f.user1_email = u.email 
                                 OR f.user2_email = u.email)
GROUP BY u.email 
HAVING COUNT(u.email) < 3

I would like to transform this query into tuple relational Calculus, the JOIN and the SELECT are pretty straightforward, but for the GROUP BY and the COUNT I don't know.

Thanks,

like image 329
lpostula Avatar asked Oct 01 '22 18:10

lpostula


1 Answers

As Lennart says, it's not possible to express those functions so, I decided to transform the count in another way.

First let's assert the following predicate:

Friends Predicate

Then we can say that having 2 or less friends, is having 0 friends, 1, or 2. To have 1 friend is like saying that there exists a friend (friend1) for wich Friends(me, friend1) is true.

To have 2 friends, you must have 1 friend and another, different. And finally you must not have any more friend.

All this can be express like this:

Querry

like image 113
lpostula Avatar answered Oct 26 '22 22:10

lpostula