用于组合两个表和混洗结果的SQL查询创建

时间:2012-06-27 02:46:16

标签: mysql sql

我想创建一个选择的SQL查询  在我的数据库中的女性图片然后在选择男性图片之后随机化图片而不是随机化它们。例如,有40张女孩照片和60张男孩照片。我希望女孩的前40张照片被选中(洗牌,然后剩下的男孩照片被选中(洗牌)

希望我很清楚。我有两个表“userID”字段是链接这两个表的字段。

  

用户表(年龄,用户ID,性别)|图片表(UserID,   numberoflikes,picure_location)

无论如何我可以生成此查询吗?

2 个答案:

答案 0 :(得分:2)

SELECT picure_location
FROM Picture
  INNER JOIN User ON Picture.UserID=User.UserID
ORDER BY gender,RAND()

您可能需要ORDER BY GENDER DESC, RAND(),具体取决于您代表性别的方式。

答案 1 :(得分:0)

请尝试以下方法:

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;