我有一张包含一些用户信息、性别、出生日期、“类别”等的表格
我需要随机抽样,但结果如下:
75% 女性
25% 男性
50% 25-35 岁
40% 36-40岁
10% 41-60 岁
共2000
记录。
无论如何可以直接在 MySQL 中执行此操作吗?
我有一张包含一些用户信息、性别、出生日期、“类别”等的表格
我需要随机抽样,但结果如下:
75% 女性
25% 男性
50% 25-35 岁
40% 36-40岁
10% 41-60 岁
共2000
记录。
无论如何可以直接在 MySQL 中执行此操作吗?
对于每个 sql 查询,您不能在 Union 语句中使用 order by 或 limit。它们可以在最后使用。
所以最好使用存储过程来输出。
CREATE PROCEDURE USER_DATA_RAND()
BEGIN
CREATE TEMPORARY TABLE USER_TMP
ID INT,
DATE_OF_BIRTH DATE,
CATEGORY STRING,
AGE INT)
INSERT INTO USER_TMP
select sex, date_of_birth, `category`,age from users where age between 25 and 35 and sex = 'male' order by rand() limit 2000*0.5*0.25) ;
INSERT INTO USER_TMP
select sex, date_of_birth, `category`,age from users where age between 25 and 35 and sex = 'female' order by rand() limit 2000*0.5*0.75) ;
INSERT INTO USER_TMP
select sex, date_of_birth, `category`,age from users where age between 36 and 40 and sex = 'male' order by rand() limit 2000*0.40*0.25) ;
INSERT INTO USER_TMP
select sex, date_of_birth, `category`,age from users where age between 36 and 40 and sex = 'female' order by rand() limit 2000*0.40*0.75) ;
INSERT INTO USER_TMP
select sex, date_of_birth, `category`,age from users where age between 41 and 60 and sex = 'male' order by rand() limit 2000*0.10*0.25) ;
INSERT INTO USER_TMP
select sex, date_of_birth, `category`,age from users where age between 41 and 60 and sex = 'female' order by rand() limit 2000*0.10*0.75) ;
SELECT * FROM USER_TMP;
END