Postgresql -从SELECT中排除一些结果

Postgresql - exclude some results from SELECT

本文关键字:结果 排除 SELECT Postgresql      更新时间:2023-10-16

我有一个名为"friendship"的表,它的列是这样的:

|from|to|status|其中"from"answers"to"引用用户名,"status"为"a"表示接受,"d"表示拒绝,"p"表示挂起。

我想从一个用户中选择所有的朋友,并把他们放在一个单独的列。这可能吗?

为了认识所有的用户朋友,我做了这样的事情:

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

现在我需要某种方法获得除'john'之外的所有名称,并将它们放在单独的列中。

我也在用c++做这个…那么,我可以使用PQgetvalue来帮助我实现这一点吗?

您可以使用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,如果产生dps):

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'

作为旁注,"from"是一个糟糕的列名…(这是一个保留词)

可以使用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';