2013-05-31 83 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

这真的很好!非常感谢你! :) –