Reputation: 689
Suppose, I have a table like this:
+---------+------------------+
| 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 |
+---------+------------------+
In a nutshell, in this table I contain users posts, and I'd like to show something like a timeline. All the records, which have original_post_id=0
- are the original posts, and must be shown in any case. But all the records with original_post_id!=0
- are the reposted, so I'd like to show them just one time. So, as a result, I need something like this:
+---------+------------------+
| post_id | original_post_id |
+---------+------------------+
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 2 |
| 6 | 0 |
| 7 | 1 |
| 10 | 0 |
| 11 | 0 |
| 12 | 3 |
+---------+------------------+
As I understand, I have to use GROUP BY
, but how exactly?
Upvotes: 1
Views: 58
Reputation: 1269763
You can do this using a single group by
, but it is tricky:
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);
Upvotes: 3
Reputation: 438
you can try this:
SELECT * FROM tableName
Where original_post_id = 0
Union
SELECT * FROM tableName
Where original_post_id != 0
Group by original_post_id
Upvotes: 0