SQL:如何使用查询的值作为另一个查询的字段?

时间:2012-03-08 00:52:53

标签: sql postgresql

user_object:

  id |  group | object_id 
-----+--------+------------
  1  |  admin | 30
  2  |  user  | 40
  3  |  user  | 50

object_permissions:

  id  | name | user   | admin 
------+------+--------+--------
  30  | foo  | false  | true
  40  | bar  | false  | false
  50  | baz  | true   | true

我希望上面的例子有所帮助。我想要类似下面这样的东西。我想如果有可能会有子查询和可能的eval。

SELECT u.id
     , o.name
     , o.<u.group>        as permissions
FROM   user_object        u
JOIN   object_permissions o
       ON (u.object_id = o.id);
----------------------------
  id |  name | permissions
-----+-------+--------------
  1  |  foo  | true
  2  |  bar  | false
  3  |  baz  | true

1 个答案:

答案 0 :(得分:1)

假设admin / user是user_object的group列中出现的唯一值,请尝试:

SELECT u.id
     , o.name
     , CASE WHEN u.group = 'admin'
          THEN o.admin 
          ELSE o.user
       END AS permissions
FROM   user_object        u
JOIN   object_permissions o
       ON (u.object_id = o.id);