2013-05-31 157 views
0

我有一個名爲「友誼」的表,其列如下:Postgresql - 從SELECT中排除一些結果

| from | to | status |其中「from」和「to」用於用戶名,「status」用於接受,'d'用於拒絕,'p'用於未決。

我想選擇一個用戶的所有朋友,並把它們放在一個單獨的列..是否有可能?

要知道所有的用戶朋友我是這樣的:

SELECT to,from,status FROM friendship 
WHERE to = 'john' AND status = 'a' 
OR from = 'john' AND status = 'a' 

現在我需要要想辦法讓所有名字中的「約翰」,並把它們放在一個單獨的collumn ..

我m也使用C++來做到這一點..所以有什麼辦法可以使用PQgetvalue來幫助我實現這個目標嗎?

+0

所以,你想顯示所有已經接受朋友的請求,無論是從約翰還是約翰,並顯示「其他」作爲一個單獨的列? –

回答

0

可以使用UNION操作

SELECT "to" as name FROM "friendship" 
WHERE "from" = "john" AND "status" = 'a' 
UNION 
SELECT "from" as name FROM "friendship" 
WHERE "to" = 'john' AND "status" = 'a'; 
+3

請注意反引號是無效的PostgresSQL語法; PostgreSQL使用ANSI引用('「identifier」'not \''identifier' \')。 –

1

你可以使用一個case聲明:

select case 
     when "to" = 'john' then "from" 
     else "to" 
     end as friend 
from friendship 
where status = 'a' 
and ("from" = 'john' or "to" = 'john') 

還是一個union all(或union,如果產生的DUP):

select "to" as friend 
from friendship 
where status = 'a' 
and "from" = 'john' 
union all 
select "from" as friend 
from friendship 
where status = 'a' 
and "to" = 'john' 

作爲一個側面說明,「來自」是一個可怕的專欄名稱...(這是一個reserv )

+0

這真的很好!非常感謝你! :) –