简体   繁体   中英

SQL Query: Grouping the latest messages using SQL JOIN

I am trying to retrieve the latest messages about each post from different users using SQL. I have 3 tables:

  • The Users Table (To collect user Information)
  • The Post Table (To Collect post information)
  • The Messages Table (Table containing messages)

However, I am getting an error with my SQL Syntax, Here is the code

SELECT
   MAX(sequence) AS latestmsg,
   COUNT(*) AS msgcount,
   sequence,
   messageid,
   username,
   receipient,
   message,
   datestamp 
FROM
   messages 
   JOIN
      users 
      ON messages.username = users.username 
   JOIN
      posts 
      ON posts.postid = messages.messageid 
WHERE
   messages.receipient = 'try-2a' 
GROUP BY
   messages.messageid 
ORDER BY
   messages.sequence DESC

Error: Column 'username' in field list is ambiguous

Link to Fiddle with Schema

SELECT
       MAX(sequence) AS latestmsg,
       COUNT(*) AS msgcount,
       sequence,
       messageid,
       users.username,
       receipient,
       message,
       datestamp 
    FROM
       messages 
       JOIN
          users 
          ON messages.username = users.username 
       JOIN
          posts 
          ON posts.postid = messages.messageid 
    WHERE
       messages.receipient = 'try-2a' 
    GROUP BY
       messages.messageid 
    ORDER BY
       messages.sequence DESC

Try the modified query below:

SELECT sequence AS latestmsg,
    msgcount,
    sequence,
    messages.messageid,
    users.username,
    receipient,
    message,
    messages.datestamp 
FROM messages 
JOIN users ON messages.username = users.username 
JOIN posts ON posts.postid = messages.messageid 
JOIN (
    SELECT messageid, MAX(sequence) AS max_seq, COUNT(*) AS msgcount
    FROM messages
    GROUP BY messageid
) m ON m.messageid = messages.messageid AND m.max_seq = messages.sequence
WHERE messages.receipient = 'try-2a' 
ORDER BY messages.sequence DESC

The username column in the SELECT list needs to have the table alias prefixed, since username exists in both messages and users

SELECT
   MAX(sequence) AS latestmsg,
   COUNT(*) AS msgcount,
   sequence, 
   messageid,
   username, --This column needs to have the alias prefix
   receipient,
   message,
   datestamp 

If you are trying to find the most recent message for each user, you would want to group by user, then find the max timestamp of each message in each user group. You can use that to then select the message with that timestamp matching it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM