假设我有一张这样的表:
+---------+------------------+
| post_id | original_post_id |
+---------+------------------+
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 2 |
| 5 | 2 |
| 6 | 0 |
| 7 | 1 |
| 8 | 1 |
| 9 | 1 |
| 10 | 0 |
| 11 | 0 |
| 12 | 3 |
+---------+------------------+
简而言之,在此表中我包含用户帖子,我想展示类似时间轴的内容。所有具有original_post_id=0
的记录都是原始帖子,并且必须在任何情况下显示。但所有带original_post_id!=0
的记录都是重新发布的,所以我想只展示一次。所以,结果,我需要这样的东西:
+---------+------------------+
| post_id | original_post_id |
+---------+------------------+
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 2 |
| 6 | 0 |
| 7 | 1 |
| 10 | 0 |
| 11 | 0 |
| 12 | 3 |
+---------+------------------+
据我了解,我必须使用GROUP BY
,但具体如何?
答案 0 :(得分:3)
您可以使用单个group by
执行此操作,但这很棘手:
select min(post_id) as post_id, min(original_post_id)
from t
group by original_post_id,
(case when original_post_id = 0 then post_id end);
答案 1 :(得分:0)
你可以试试这个:
SELECT * FROM tableName
Where original_post_id = 0
Union
SELECT * FROM tableName
Where original_post_id != 0
Group by original_post_id