MySQL如何从相同条件范围内的两个不同子集中选择和按条件顺序排序

时间:2013-12-23 04:32:17

标签: php mysql sql

我的网站有真实世界的mysql选择问题,我的成员性别是女性或男性,但他们没有按比例分配,即70%的男性,30%的女性,

我想在网站的主页上选择显示

  1. 选择随机50名成员但确保他们是50%男性和50%女性
  2. 将这些结果排在男性和女性之间,其次是男性女性,即m,f,m,f ......等等。
  3. 如何通过单个查询实现此目的?

    例如:

    SELECT * FROM user u WHERE 1 ORDER BY rand() LIMIT 50
    

    我不想选择50%的比例,所以如果可以,请提供帮助

2 个答案:

答案 0 :(得分:2)

你有没有尝试过工会?

SELECT * FROM table WHERE gender = 1 LIMIT 25 
UNION
SELECT * FROM table WHERE gender = 2 LIMIT 25 

答案 1 :(得分:2)

  1. SELECT RANDOM 50 MEMBERS
  2. 确保他们的男性占50%,女性占50%
  3. 订购这些结果,即M,F,M,F ...... ETC
  4. 你可以尝试一下吗?

    SET @odd := 1;
    SET @even := 2;
    
    SELECT *
    FROM
    (
        SELECT *
        FROM
        (
            SELECT @odd := @odd + 2 AS ord, users.*
            FROM users
            WHERE sex = 'M'
            ORDER BY RAND()
            LIMIT 25
        ) x
    
        UNION ALL
    
        SELECT *
        FROM
        (
            SELECT @even := @even + 2 AS ord, users.*
            FROM users
            WHERE sex = 'F'
    
            ORDER BY RAND()
            LIMIT 25
        ) y
    ) z
    ORDER BY ord;
    

    示例输出

    +------+------+------+
    | ord  | id   | sex  |
    +------+------+------+
    |    3 |    1 | M    |
    |    4 |    8 | F    |
    |    5 |    2 | M    |
    |    6 |    9 | F    |
    |    7 |    3 | M    |
    |    8 |   10 | F    |
    

    我的第一种方法是这样的

    SET @odd := 1;
    SET @even := 2;
    
    SELECT *
    FROM
    (
        SELECT @odd := @odd + 2 AS ord, users.*
        FROM users
        WHERE sex = 'M'
        ORDER BY RAND()
        LIMIT 25
    
    
        UNION ALL
    
        SELECT @even := @even + 2 AS ord, users.*
        FROM users
        WHERE sex = 'F'
        ORDER BY RAND()
        LIMIT 25
    ) x
    ORDER BY ord;
    

    但是我收到的错误如下:

     ERROR 1221 (HY000): Incorrect usage of UNION and ORDER BY