我的网站有真实世界的mysql选择问题,我的成员性别是女性或男性,但他们没有按比例分配,即70%的男性,30%的女性,
我想在网站的主页上选择显示
如何通过单个查询实现此目的?
例如:
SELECT * FROM user u WHERE 1 ORDER BY rand() LIMIT 50
我不想选择50%的比例,所以如果可以,请提供帮助
答案 0 :(得分:2)
你有没有尝试过工会?
SELECT * FROM table WHERE gender = 1 LIMIT 25
UNION
SELECT * FROM table WHERE gender = 2 LIMIT 25
答案 1 :(得分:2)
你可以尝试一下吗?
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