[英]How can I get 5 records for each 'category' with one select in MySQL?
I have table topics
: 我有餐桌topics
:
ID title body ctg_topic_id ...
1 aaa bbb 1 ...
2 aa2 bb2 2 ...
3 aa3 bb3 1 ...
4 aa4 bb4 3 ...
5 aa5 bb5 3 ...
6 aa6 bb6 1 ...
.......
105 a105 b105 23 ...
How can I get 5 records for each ctg_topic_id
by 1 select? 通过选择1如何获得每个ctg_topic_id
的5条记录?
This SQL script for mysql will give you the first five of all cats. 这个用于mysql的SQL脚本将为您提供所有猫的前五名。
SELECT * FROM your_table WHERE ctg_topic_id IN (SELECT DISTINCT ctg_topic_id from your_table) GROUP BY ctg_topc_id LIMIT 0,5
Via PHP. 通过PHP。 (i omit the PHP connection code) (我省略了PHP连接代码)
First, get the list; 首先,获取列表;
$stm = $pdo->preprare("SELECT DISTINCT cth_topc_id FROM my_table");
$stm->execute():
$cats = $stm->fetchAll();
$result = array();
foreach ($cats as $cat) {
$query = $pdo->prepare("SELECT * my_table WHERE cth_topic_id=? LIMIT 0,5");
$query->bindParams(1,$cat);
$pdo->execute();
$result[$i] = $query->fetchAll();
}
This simplified code should produce a matrix containing N arrays (where N is the number of distinct cats) that contains an array of 5 elements of the result set. 此简化的代码应生成一个包含N个数组的矩阵(其中N是不同的猫的数量),该矩阵包含结果集的5个元素的数组。
I've not checked the code so any hints will be corrected thanks. 我没有检查代码,所以任何提示都会得到纠正,谢谢。
One problem is that LIMIT 0,5 will get the first 5 items, withot any logic. 一个问题是,LIMIT 0,5将获得前5个项目,而没有任何逻辑。 If you want to sort use ORDER BY for example by ('date') etc. 如果要排序,请使用ORDER BY,例如按('date')等。
SELECT ctg_topic_id from something, GROUP BY ctg_topic_id....
它将选择所有类别。
You can not. 你不能。 You can do it with one query using UNION or read this How to select the first/least/max row per group in SQL 您可以使用UNION进行一次查询,也可以阅读此方法如何在SQL中选择每个组的第一行/最小行/最大行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.