2016-09-30 28 views
0

我的查詢是:試圖讓只有1結果出來一個SQL查詢返回整個列表包括重複

SELECT * FROM <table> 

這將導致以下:

 
    ID | Description | Foreign_ID 

    1 | 5060:Stat | 4321 

    2 | 5060:Stat | 4321 

    3 | 7060:Pleb | 5423 

    4 | 5060:Stat | 4321 

    5 | 7070:Pleb | 5423 

    6 | 6509:Stat | 4321 

我怎樣才能返回以下哪裏我只能從具有相同foreign_ID的記錄中獲得1條記錄?像:

 
1 | 5060:Stat | 4321 

3 | 7060:Pleb | 5423 

回答

0

使用distinct on

select distinct on (foreign_id) t.* 
from t 
order by foreign_id; 

這將返回的任意行。如果你想在一個具有最小id

SELECT * FROM <Table> GROUP BY Foreign_ID 
0

您可以通過外部ID使用GROUP BY分組查詢也可能想要使用order by子句

select distinct on (Foreign_ID) 
ID, Description, Foreign_ID 
from <table> 
order by ID 
0

使用distinct on條款

select distinct on (Foreign_ID) 
ID, Description, Foreign_ID 
from <table> 

您:

order by foreign_id, id;