简体   繁体   中英

How can I get 5 records for each 'category' with one select in MySQL?

I have table 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?

This SQL script for mysql will give you the first five of all cats.

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. (i omit the PHP connection code)

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.

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. If you want to sort use ORDER BY for example by ('date') etc.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM