我想创建一个 SQL 查询,在我的数据库中选择女性的图片,然后在选择男性图片之后随机化这些图片,而不是随机化它们。例如,有 40 张女孩的照片和 60 张男孩的照片。我想要选择第 40 张女孩的照片(洗牌,然后选择剩余的男孩照片(洗牌)
希望我很清楚。我有两个表,“userID”字段是链接两个表的字段。
用户表(年龄、用户ID、性别)| 图片表( UserID , numberoflikes , picure_location )
无论如何我可以生成这个查询吗?
SELECT picure_location
FROM Picture
INNER JOIN User ON Picture.UserID=User.UserID
ORDER BY gender,RAND()
ORDER BY GENDER DESC, RAND()
根据您代表性别的方式,您可能需要。
请尝试以下方法:
SET @num1=0, @num2=0;
SELECT t1.*, p1.picturelocation,t2.*, p2.picturelocation
FROM (
SELECT UserID,gender, @num1:=@num1+1 AS num
FROM UserTable WHERE gender='Female'
) AS t1
INNER JOIN (
SELECT UserID,gender, @num2:=@num2+1 AS num
FROM (
SELECT *
FROM UserTable WHERE gender='Male'
ORDER BY RAND()
LIMIT 40
) AS t
) AS t2
ON t1.num = t2.num
INNER JOIN PictureTable p1 on t1.userid=p1.userid
INNER JOIN PictureTable p2 on t2.userid=p2.userid;