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.