Reputation: 2843
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?
Upvotes: 1
Views: 4021
Reputation: 645
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.
Upvotes: 1
Reputation: 158
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
Upvotes: 0
Reputation: 971
SELECT ctg_topic_id from something, GROUP BY ctg_topic_id....
it will select all the categories..
Upvotes: 0