0

I've created the function, but have some mistakes. I understand the logic, but can't connect it.Maybe you will be able to help me to understand it.

Given database schema:

• Contacts (user ID, fname, lname, cell, city, country) PK(user ID)

• Conversation (convID, duration) PK(convID)

• Messages (msgID, sender ID, time sent, convID, msg text, spam) PK(msgID) FK(sender ID) → Contacts(user ID) FK(convID) → Conversation(convID)

• Recipients (msgID, user ID, time read) PK(msgID,user ID) FK(msgID) → Messages(msgID) FK(user ID) → Contacts(user ID)

Question:

Create a function, called get max duration(msgID) that will calculate the duration in seconds of the conversation that the message belongs to. The duration should be found based on the following calculation: CONV DURATION = MAX(message.time read) - MIN(message.time sent) That is, for a specific conversation duration, you need to find the latest read message and the earliest sent message. You may find useful using the following temporal built-in function extract (seconds from [time])

My solution:

CREATE OR REPLACE FUNCTION get_max_duration(msgID int) 
RETURNS INTEGER

AS $$
    DECLARE msgID Integer;
         CONV_DURATION Integer;

    BEGIN
        Select Conversation.conv_ID
        FROM Conversation
        INNER JOIN Message M on Conversation.conv_ID = M.conv_ID
        WHERE time_sent = MIN(message.time_sent)
        GROUP BY Conversation.conv_ID;

        SELECT Message. msg_ID
        FROM Message
        JOIN Recipient R on Message.msg_ID = R.msg_ID
        WHERE time_read = MAX(message.time_read)
        GROUP BY Message. msg_ID;

        Select Conversation.duration
        FROM Conversation
        WHERE duration = CONV_DURATION
        GROUP BY Conversation.duration;


        SELECT CONV_DURATION = TIMESTAMP  (MAX(message.time_read) - MIN(message.time_sent));
       RETURN CONV_DURATION;
    end;

$$ LANGUAGE plpgsql;
Alex
  • 11
  • 2
  • That syntax has little connection to proper PL/pgSQL. You should read the documentation and look at the examples therein. – Laurenz Albe Apr 15 '22 at 06:03
  • To store a value from a query in a variable you can use this syntax: SELECT column_name INTO my_variable (rest of the query....); so something like SELECT Message.msg_ID INTO my_max_id FROM Message .... – Sotis Apr 15 '22 at 13:36
  • can you be more specific please? – Alex Apr 15 '22 at 17:40

0 Answers0