Reputation: 151
I'm trying to get 10 random rows from table 'users', along with the matching profile picture from table 'Profile_pictures'.
My query so far:
SELECT u.id, u.username, u.status, p.file_name
FROM users AS u, profile_pictures AS p
WHERE p.status = 1 AND u.status != 3 AND u.status != 4
AND RAND()<(SELECT ((1/COUNT(*))*10) FROM users AS u)
GROUP BY u.id
ORDER BY RAND()
LIMIT 7
The problem is that it is getting the same profile picture for all of the rows.
I really, really hope that you can help me out.
Upvotes: 0
Views: 75
Reputation: 1269753
If you want to get 10 random rows from users, then you should do the selection from users
in a subquery before the join:
SELECT u.id, u.username, u.status, p.file_name
FROM (select u.*
from users u
where u.status <> 3 AND u.status <> 4
order by rand()
limit 10
) u7 join
profile_pictures p
on u.id = p.user_id and p.status = 1;
This also fixes the join notation. If you want 10 random pictures from users, you can do the selection after the join:
SELECT u.id, u.username, u.status, p.file_name
FROM users u join
profile_pictures p
on u.id = p.user_id
where u.status <> 3 AND u.status <> 4 and p.status = 1
order by rand()
limit 10;
By the way, this also fixes the join. Presumably there is a user id field connecting the pictures to the users.
Upvotes: 1
Reputation: 27247
Use a LEFT JOIN statement to match users with their pictures. I'm assuming profile_pictures has a column called user_id to use to match them. The LEFT JOIN will return users regardless of them having a picture or not. If you want to return only users that have pictures, then use an INNER JOIN instead.
SELECT u.id, u.username, u.status, p.file_name
FROM users AS u
LEFT JOIN profile_pictures AS p ON u.id = p.user_id
WHERE p.status = 1 AND u.status != 3 AND u.status != 4
ORDER BY RAND()
LIMIT 7
The line RAND()<(SELECT ((1/COUNT(*))*10) FROM users AS u)
didn't look necessary so I took it out. What was it there for?
Upvotes: 0