如何在postgresql中使用SELECT EXISTS时返回多个值

时间:2013-12-27 14:26:38

标签: sql postgresql

我有以下SQL查询:

SELECT EXISTS (SELECT r.id FROM Rules r INNER JOIN rule_t c on c.id=r.rule_t.id 
INNER JOIN user u on u.id = r.user_id
WHERE u.fmnum='2813'
AND c.name='default') ::int

有没有办法可以修改它,以便我得到两个值,EXISTS方法的INT和r.id?

我知道我可以更改查询以便删除EXISTS方法...如果子选择返回任何内容,那么我知道记录存在...但我只是想知道它是否可以做以上。

感谢。

编辑1

我正在pgadmin3 ...

的新查询窗口中测试以下代码
SELECT *
FROM  (
   SELECT TRUE, r.id
   FROM   rules  r
   JOIN   rule_t c on c.id = r.rule_t.id 
   JOIN   user   u on u.id = r.user_id
   WHERE  u.fmnum = '2813'
   AND    c.name = 'default'
   );

但我收到以下错误:

  

错误:FROM中的子查询必须有一个别名LINE 2 :(           ^提示:例如,FROM(SELECT ...)[AS] foo。

编辑2

SELECT *
FROM  (
   SELECT TRUE, r.id
   FROM   rules  r
   JOIN   rule_t c on c.id = r.rule_t.id 
   JOIN   user   u on u.id = r.user_id
   WHERE  u.fmnum = '2813'
   AND    c.name = 'default'
   ) AS x;

1 个答案:

答案 0 :(得分:1)

SELECT 1 AS does_exist, r.id
FROM   rules  r
JOIN   rule_t c on c.id = r.rule_t.id 
JOIN   user   u on u.id = r.user_id
WHERE  u.fmnum = '2813'
AND    c.name = 'default'
LIMIT  1;  -- may or may not be needed.

这就是你似乎要求的:你得到两列。但如果找不到任何内容,你会得到 no row

如果你想要一行,即使找不到任何内容,你也需要一个子查询:

SELECT sub.t_id IS NOT NULL AS does_exist, sub.id
FROM  (SELECT 1) x  -- dummy to guarantee 1 row
LEFT JOIN (         -- LEFT JOIN is crucial
    SELECT r.id
    FROM   rules  r
    JOIN   rule_t c on c.id = r.rule_t.id 
    JOIN   user   u on u.id = r.user_id
    WHERE  u.fmnum = '2813'
    AND    c.name = 'default'
    LIMIT  1        -- may or may not be needed.
    ) ON TRUE;      -- join condition is always true

或者,更简单/更快:

SELECT 1 AS does_exist, r.id
FROM   rules  r
JOIN   rule_t c on c.id = r.rule_t.id 
JOIN   user   u on u.id = r.user_id
WHERE  u.fmnum = '2813'
AND    c.name = 'default'

UNION  ALL
SELECT 0, NULL
LIMIT  1;