mysql 分组后 每组随机取一条记录 求sql语句
如题,大家帮我想想SQL语句怎么写,数据库是mysql如下表:idtypestr10aaa20bbb31sss41ddd52ggg62hhh比如我把表里的记录按type分...
如题,大家帮我想想SQL语句怎么写,数据库是mysql
如下表:
id type str
1 0 aaa
2 0 bbb
3 1 sss
4 1 ddd
5 2 ggg
6 2 hhh
比如我把表里的记录按type分成3组,每组要随机出一条记录,那么我要的结果就是3条type不同的随机的记录。关键是随机,不是max、min 展开
如下表:
id type str
1 0 aaa
2 0 bbb
3 1 sss
4 1 ddd
5 2 ggg
6 2 hhh
比如我把表里的记录按type分成3组,每组要随机出一条记录,那么我要的结果就是3条type不同的随机的记录。关键是随机,不是max、min 展开
5个回答
展开全部
CREATE TABLE test_gd2gd2(
id INT,
type INT,
str CHAR(3)
);
INSERT INTO test_gd2gd2
SELECT 1, 0, 'aaa' UNION ALL
SELECT 2, 0, 'bbb' UNION ALL
SELECT 3, 1, 'sss' UNION ALL
SELECT 4, 1, 'ddd' UNION ALL
SELECT 5, 2, 'ggg' UNION ALL
SELECT 6, 2, 'hhh';
mysql> SELECT
-> type,
-> (SELECT str FROM test_gd2gd2 sub
-> WHERE type = main.type ORDER BY rand()
-> LIMIT 0,1) AS Rstr
-> FROM
-> test_gd2gd2 main
-> GROUP BY
-> type;
+------+------+
| type | Rstr |
+------+------+
| 0 | bbb |
| 1 | ddd |
| 2 | hhh |
+------+------+
3 rows in set (0.01 sec)
mysql> SELECT
-> type,
-> (SELECT str FROM test_gd2gd2 sub
-> WHERE type = main.type ORDER BY rand()
-> LIMIT 0,1) AS Rstr
-> FROM
-> test_gd2gd2 main
-> GROUP BY
-> type;
+------+------+
| type | Rstr |
+------+------+
| 0 | aaa |
| 1 | sss |
| 2 | hhh |
+------+------+
3 rows in set (0.00 sec)
id INT,
type INT,
str CHAR(3)
);
INSERT INTO test_gd2gd2
SELECT 1, 0, 'aaa' UNION ALL
SELECT 2, 0, 'bbb' UNION ALL
SELECT 3, 1, 'sss' UNION ALL
SELECT 4, 1, 'ddd' UNION ALL
SELECT 5, 2, 'ggg' UNION ALL
SELECT 6, 2, 'hhh';
mysql> SELECT
-> type,
-> (SELECT str FROM test_gd2gd2 sub
-> WHERE type = main.type ORDER BY rand()
-> LIMIT 0,1) AS Rstr
-> FROM
-> test_gd2gd2 main
-> GROUP BY
-> type;
+------+------+
| type | Rstr |
+------+------+
| 0 | bbb |
| 1 | ddd |
| 2 | hhh |
+------+------+
3 rows in set (0.01 sec)
mysql> SELECT
-> type,
-> (SELECT str FROM test_gd2gd2 sub
-> WHERE type = main.type ORDER BY rand()
-> LIMIT 0,1) AS Rstr
-> FROM
-> test_gd2gd2 main
-> GROUP BY
-> type;
+------+------+
| type | Rstr |
+------+------+
| 0 | aaa |
| 1 | sss |
| 2 | hhh |
+------+------+
3 rows in set (0.00 sec)
展开全部
在sqlserver中用的是top关键字 比如查询user表
select * from user limit 1 ;这就可以了,, 另外 mysql 中的翻页很方便的。比sqlserver中的简单多了。
select * from user limit 1 ;这就可以了,, 另外 mysql 中的翻页很方便的。比sqlserver中的简单多了。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
SELECT * FROM (SELECT * FROM tablename ORDER BY RAND()) as a GROUP BY a.type
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
select * from table order by rand() limit 0,1;
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
wangzhiqing999 , holychuo答案均正确,但 wangzhiqing999 好象要强一点,学习了
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询