存在子查询-返回单列

时间:2019-04-11 23:03:14

标签: postgresql amazon-web-services aws-lambda

我的查询:

class Client: UIViewController {

    func showAlert() {
        self.presentTextFieldAlert(title: "Hello", message: "Write sth", textFieldPlaceholder: "Write here") { (result) in
            if let result = result {
                // User entered some text and tapped OK.
            }
        }
    }
}

返回5列false |错误错误错误错误

https://imgur.com/a/XdI9gKF

我如何将它们分成一列?我可以使用order by吗?

这样做的原因是因为当我在AWS Lamba / CloudWatch中返回查询时,它只给我该行的第一个值(1个假值),而不是全部5个值。

https://imgur.com/a/MaZa41k

EDIT1:__________________________________________________________________

我有5个值的数组[postId1,postId2,postId3,postId4,postId5]

我想检查我的表“ votes”是否包含数组的每个值。

这就是为什么我使用上面的五个“ EXIST”查询。 该查询本身可以在pgadmin中完美运行,并返回五个假值。

https://imgur.com/a/XdI9gKF

但是在AWS Cloudwatch中,它仅返回1列(值为1的false)

https://imgur.com/a/MaZa41k

这是我不确定问题出在哪里。是因为nodejs-postgres不允许在单个查询中包含多个SELECT语句吗?

基本上,这是AWS Lambda返回五个“假”值的最终目标。

SELECT EXISTS (SELECT votes FROM voted WHERE id = $1 AND user_id = $6),
    EXISTS (SELECT votes FROM voted WHERE id = $2 AND user_id = $6),
    EXISTS (SELECT votes FROM voted WHERE id = $3 AND user_id = $6),
    EXISTS (SELECT votes FROM voted WHERE id = $4 AND user_id = $6),
    EXISTS (SELECT votes FROM voted WHERE id = $5 AND user_id = $6);

2 个答案:

答案 0 :(得分:0)

您可以按照以下方式进行操作

a <- ndf %>%  group_by(BRAND, VARIANT)  %>% summarise_all(funs(n()))

因此它将返回

select 
to_jsonb(array_agg(main)) as "rows"

      from (SELECT EXISTS (SELECT votes FROM voted WHERE id = $1 AND user_id = $6) as a,
        EXISTS (SELECT votes FROM voted WHERE id = $2 AND user_id = $6) as b,
        EXISTS (SELECT votes FROM voted WHERE id = $3 AND user_id = $6) as c,
        EXISTS (SELECT votes FROM voted WHERE id = $4 AND user_id = $6) as d,
        EXISTS (SELECT votes FROM voted WHERE id = $5 AND user_id = $6) as e) as main;   

答案 1 :(得分:0)

如果只需要一列,则可以将结果转换为JSON值,其中包含要测试的ID的键/值对:

select jsonb_object_agg(t.id::text, coalesce(t.id = v.id, false)) as result
from unnest(array[$1,$2,$3,$4,$5]) as t(id)
  left join voted v on t.id = v.id and v.user_id = $6;

array[...]包含您要测试的ID值。

coalesce(t.id = v.id, false)也可以写为t.id is not distinct from v.id,以正确处理丢失的ID值。

结果将是一个JSON值,其中包含ID值作为键,如果表中存在ID,则返回true / false值,例如

{"5": true, "8": false, "10": false, "11": false, "22": false, "42": false, "100": false}

如果您的应用程序可以处理JSON,则它比您的方法灵活得多,因为它可以轻松扩展到更多值。