0

我有一个名为“friendship”的表,其中的列是这样的:

|从|到|状态| 其中“from”和“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 来帮助我实现这一目标吗?

4

2 回答 2

1

You could use a case statement:

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

Or a union all (or union, if this yields dups):

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'

As a side note, "from" is a terrible column name... (It's a reserved word.)

于 2013-05-31T12:30:07.267 回答
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';
于 2013-05-31T12:16:02.023 回答