简体   繁体   中英

Fetching random rows, along with matching rows from another table?

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.

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.

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?

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