2010-11-05 37 views
1
1. links: link_id, road 
2. roads: road, code 
2. admin_classes: code, admin_class, priority 

所以,對於一個LINK_ID我有幾個代碼和幾個admin_class +優先原糖 但在結果集我需要爲每個link_id只有一行: link_id和admin_class,那指的是最低優先級。 我儘量讓sql語句,像下面:SQL:如何添加條件對內部的選擇

select l.link_id, ac.admin_class, min(ac.priority) 
from base.links as l 
inner join base.admin_classes as ac 
on ac.code=l.code 
where ac.admin_class<>0 

但是,首先,它不工作,這是不是我所需要的。我想在結果集只有兩列 - link_id和admin_class

然後我嘗試以下操作:

select l.link_id, (select ac.admin_class from base.admin_classes as ac where ac.code=l.code 
order by ac.priority limit 1) as admin_class from base.links as l 

這是正確的,但我不知道如何在內部選擇添加條件,我只需要admin_class原糖<> 0

我使用PostgreSQL 8.3

預先感謝您。

回答

0

這不工作?

inner join base.admin_classes as ac 
on ac.code=l.code and ac.admin_class<>0 
1

我不熟悉PostgreSQL的,但我猜原始查詢不起作用becuse你有沒有group by

然而一個min()聚合功能,下面應該,如果你不工作「T需要min()

select l.link_id, ac.admin_class 
from base.links as l 
inner join base.admin_classes as ac 
     on ac.code=l.code 
     and ac.admin_class<>0 

否則,請嘗試:

select l.link_id, ac.admin_class, min(ac.priority) 
from base.links as l 
inner join base.admin_classes as ac 
     on ac.code=l.code 
     and ac.admin_class<>0 
group by l.link_id, ac.admin_class 
+0

對不起,我試圖簡化和寫錯了))我們遵循表1:link_id,代碼。表2:身份證,代碼,道路。 table3:道路,admin_class,優先級。所以我們有一個link_id和一個link_id從表3幾條道路,但我們希望得到link_id + admin_class具有最小優先權) – user498274 2010-11-05 12:26:08

+0

感謝您的回答)但我只需要在結果集中的兩列,因爲我在imsert中使用它clouse((和最後一條語句將返回followng原始1-2-2,1-3-2,1-4-2一個link_id = 1,但我只需要一行link_id – user498274 2010-11-05 12:37:40

0

好吧,我不知道很多關於PostgreSQL的,但這是它是如何與T-SQL來完成:

select l.link_id, ac.admin_class, min(ac.priority) 
from base.links as l 
inner join base.admin_classes as ac 
on ac.code=l.code 
group by l.link_id, ac.admin_class 
having ac.admin_class <> 0 
+0

我相信'有'子句只有在您將其與聚合本身結合使用時才真正有必要。改變它'在哪裏'並且移動'group by'上方的行也將起作用:-) – 2010-11-05 12:24:17

+0

我誤會了(我有一個link_id來自admin_classes的原始數據,所以你的請求會像這樣返回水平:1-2-2,1 -3-2等,但我只需要一行鏈接id和只有兩列,因爲我在插入子句中使用它 – user498274 2010-11-05 12:42:01

1

我相信你應該做兩兩件事。

1日創建一個視圖名爲viewAdminRoads


CREATE VIEW viewAdminRoads 
AS 
SELECT 
roads.code, 
roads.road, 
admin_classes.admin_class, 
admin_classes.priority 
FROM roads 
INNER JOIN admin_classes 
     ON roads.road 
     = admin_classes.road 
WHERE admin_classes.priority <> 0 

建立這些視圖簡化了整個過程

第二屆創建您的選擇


SELECT 
link.link_id, 
MIN(viewAdminRoads.priority) as priority 
FROM links 
INNER JOIN viewAdminRoads 
     ON links.code 
     = viewAdminRoads.code 
GROUP BY link.link_id 

記住,觀點是你的frien d。

+0

我同意,但我們的項目政治不接受意見。但我已經解決了我的問題,使用子選擇。謝謝你的回答 – user498274 2010-11-06 19:22:55