2017-03-22 182 views
1

想,我有這樣的一個表:GROUP BY在MySQL查詢

+---------+------------------+ 
| 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,但究竟如何?

回答

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); 
+0

真棒!就是這樣! –

0

你可以試試這個:

SELECT * FROM tableName 
Where original_post_id = 0 
Union 
SELECT * FROM tableName 
Where original_post_id != 0 
Group by original_post_id