0

I want to join two tables and return a random field from the second table because there are multiple matches when joining.

For example. I have a users table and a user_posts table. I want to select each user's id, and a random post id and the post's message that they have in the user_posts table. Each user can have multiple posts in the user_posts table.

This answer explains what I'm trying to do, but it's not working. Here's my query:

SELECT user_id, post_id, message FROM (
    SELECT users.id AS user_id, user_posts.id AS post_id, message
    FROM users INNER JOIN user_posts ON users.id = user_id
    ORDER BY RAND()
) AS a GROUP BY user_id

For testing, I added two rows in the user_posts table for user with id of 1 but it's retrieving the same post every time.

Community
  • 1
  • 1
Altherat
  • 701
  • 1
  • 13
  • 21

1 Answers1

0

using cross apply to get random one post and join to users to display

 select u.id,RandomPostbyUser.* 
     from users u
     cross apply (     
        SELECT  user_posts.id AS post_id, message
        FROM users u1 INNER JOIN user_posts ON u1.id = u.id
        order by RAND()
        LIMIT 1) RandomPostbyUser
RoMEoMusTDiE
  • 4,739
  • 1
  • 17
  • 26