mysql 分组后 每组随机取一条记录 求sql语句
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mysql 分组后 每组随机取一条记录 求sql语句相关的知识,希望对你有一定的参考价值。
如题,大家帮我想想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 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) 参考技术A 在sqlserver中用的是top关键字 比如查询user表
select * from user limit 1 ;这就可以了,, 另外 mysql 中的翻页很方便的。比sqlserver中的简单多了。
参考技术B SELECT * FROM (SELECT * FROM tablename ORDER BY RAND()) as a GROUP BY a.type 参考技术C select * from table order by rand() limit 0,1; 参考技术D wangzhiqing999 , holychuo答案均正确,但 wangzhiqing999 好象要强一点,学习了
如何用SQL SERVER取分组数据第一条
参考技术A根据table1_id进行分组所得结果:
select * from (select a.id as a_id,a.name,a.time,a.content,b.id as b_id,b.user from table1 a inner join table2 b on a.id = b.table1_ID) new_tbl where b_id in (select min(id) from table2 group by table1_ID)
扩展资料:
注意事项
在SQL Server数据库中,使用top关键字:SELECT TOP number|percent column_name(s) FROM table_name
在MySQL数据库中,使用LIMIT关键字:SELECT column_name(s) FROM table_name LIMIT number
例子:SELECT * FROM Persons LIMIT 1
select bookName from book where price > 20 limit 1;
limit 1;
or
limit 0,1;
在Oracle数据库中,使用ROWNUM关键字:
SELECT column_name(s) FROM table_name WHERE ROWNUM <= number
例子:SELECT * FROM Persons WHERE ROWNUM <= 1
以上是关于mysql 分组后 每组随机取一条记录 求sql语句的主要内容,如果未能解决你的问题,请参考以下文章