2012-04-04 18 views
0

所以我得到這個查詢,並將其從表中獲取這樣的:如何在查詢中告訴我不想重複?

種植表

PLANT ID, Color Description 
1   Red 
2   Green 
3   Purple 

蔬菜表

VegetabkeID, PLANT ID, Feeldesc 
199   1  Harsh 
200   1  Sticky 
201   2  Bitter 
202   3  Bland 

,現在我的查詢我他們利用植物ID連接(我使用左連接)

PLANT ID, Color Description, Feeldesc 
1   Red    Harsh    
1   Red    Sticky 
2   Green    Bitter 
3   Purple   Bland 

因此,pr問題是在查詢中你可以看到紅色顯示兩次!我不能有這個,我不知道如何使聯接發生,但停止紅色來了兩次。在文檔中

+2

對於兩個'Red'條目,你有不同的'Feeldesc'值,所以你想返回哪一個? – sll 2012-04-04 18:34:41

+1

你會如何像上面的結果一樣發生?由於「紅色嚴酷」和「紅色粘滯」同樣正確,你想消除一個,你需要決定一個規則。 – 2012-04-04 18:34:57

+0

好吧,你想從蔬菜表中選擇哪一行? – dotjoe 2012-04-04 18:35:01

回答

1

似乎遠程可能,你問如何組指示 - 也就是說,顯示一個值標識或描述一個只在該組的第一行上分組。在這種情況下,你想使用lag()窗口函數。

假設的模式和數據的設置是這樣的:

select p.plantId, p.color, v.Feeldesc 
    from plant p left join vegetable v using (plantId) 
    order by plantId, vegetableId; 

如果你是:

create table plant (plantId int not null primary key, color text not null); 
create table vegetable (vegetableId int not null, plantId int not null, 
      Feeldesc text not null, primary key (vegetableId, plantId)); 
insert into plant values (1,'Red'),(2,'Green'),(3,'Purple'); 
insert into vegetable values (199,1,'Harsh'),(200,1,'Sticky'), 
          (201,2,'Bitter'),(202,3,'Bland'); 

告訴你結果(模數列標題)可以用這個簡單的查詢來獲得希望在第一行之後抑制重複信息的顯示,這個查詢將會這樣做:

select 
    case when plantId = lag(plantId) over w then null 
     else plantId end as plantId, 
    case when p.color = lag(p.color) over w then null 
     else p.color end as color, 
    v.Feeldesc 
    from plant p left join vegetable v using (plantId) 
    window w as (partition by plantId order by vegetableId); 

個結果是這樣的:

plantid | color | feeldesc 
---------+--------+---------- 
     1 | Red | Harsh 
     |  | Sticky 
     2 | Green | Bitter 
     3 | Purple | Bland 
(4 rows) 

我剛剛這個星期做像上面的東西直接產生出的psql這很容易,對於最終用戶閱讀的列表;否則它永遠不會發生,你可能會問這個功能。希望這可以回答你的問題,儘管我可能完全脫離基地。

0

檢查ARRAY_AGG功能,它可以用於像這樣:

SELECT 
    v.plantId 
    ,v.color 
    ,array_to_string(array_agg(v.Feeldesc),', ') 
FROM 
    vegetable 
    INNER JOIN plant USING (plantId) 
GROUP BY 
    v.plantId 
    ,v.color 

或使用

SELECT DISTINCT 
    v.plantId 
    ,v.color 
FROM 
    vegetable 
    INNER JOIN plant USING (plantId) 

免責聲明:預期手寫,語法錯誤:)

相關問題