我有一个phpbb mysql表,它使用post_id topic_id和forum_id列创建一行。
对于每个帖子,行的数据是:
post_id topic_id forum_id
2 1 12
1 1 12
3 2 12
4 2 12
6 3 12
5 3 12
2 1 13
1 1 13
3 2 13
4 2 13
6 3 13
5 3 13
我想只获得每个topic_id的最小post_id行,以获得类似的内容:
post_id topic_id forum_id
1 1 12
3 2 12
5 3 12
1 1 13
3 2 13
5 3 13
有谁可以帮助我? (我想通过然后分组使用顺序......但是不按照我想的那样工作......
答案 0 :(得分:2)
尝试这样的事情......
select post_id, topic_id, forum_id
from thetable t
where
(post_id,topic_id) = (select min(t1.post_id), t1.topic_id
from thetable t1
where t1.topicid = t.topicid group by t1.topic_id)
这表示从subselect模式中的post_id和topic_id所在的表中获取所有记录。
答案 1 :(得分:0)
MySQL 5.6架构设置:
CREATE TABLE topic
(`post_id` int, `topic_id` int, `forum_id` int)
;
INSERT INTO topic
(`post_id`, `topic_id`, `forum_id`)
VALUES
(2, 1, 12),
(1, 1, 12),
(3, 2, 12),
(4, 2, 12),
(6, 3, 12),
(5, 3, 12),
(2, 1, 13),
(1, 1, 13),
(3, 2, 13),
(4, 2, 13),
(6, 3, 13),
(5, 3, 13)
;
查询1 :
select forum_id, topic_id, min(post_id) as min_post_id
from topic
group by forum_id, topic_id
<强> Results 强>:
| forum_id | topic_id | min_post_id |
|----------|----------|-------------|
| 12 | 1 | 1 |
| 12 | 2 | 3 |
| 12 | 3 | 5 |
| 13 | 1 | 1 |
| 13 | 2 | 3 |
| 13 | 3 | 5 |