[英]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'. 我试图从表'users'中获取10个随机行,以及从表'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: 如果要从用户那里获得10个随机行,则应在联接之前在子查询中从users
中进行选择:
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: 如果要从用户那里随机获得10张图片,可以在加入后进行选择:
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. 大概有一个用户ID字段,将图片连接到用户。
Use a LEFT JOIN statement to match users with their pictures. 使用LEFT JOIN语句将用户与其图片匹配。 I'm assuming profile_pictures has a column called user_id to use to match them. 我假设profile_pictures有一个名为user_id的列用于匹配它们。 The LEFT JOIN will return users regardless of them having a picture or not. LEFT JOIN将返回用户,无论他们是否有图片。 If you want to return only users that have pictures, then use an INNER JOIN instead. 如果只想返回有图片的用户,请改用INNER JOIN。
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. 行RAND()<(SELECT ((1/COUNT(*))*10) FROM users AS u)
看起来没有必要,所以我将其取出。 What was it there for? 那是为了什么
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.