【问题标题】:How to bash array into psql query如何将数组 bash 到 psql 查询中
【发布时间】:2022-01-06 17:48:27
【问题描述】:

我正在尝试将 bash 数组调用到 for 循环内的 psql 查询中,但我无法使其工作...

这是我目前所拥有的

#!/bin/bash

IFS=$'\n' groupids=(`psql -X -A -d files -t -c 'select id from groups where parent=127'`)

arr=${#groupids[@]}

for (( x = 0; x<arr; x++ )); do
        users=$(psql -X -A -d files -t -c "select id from groups where parent=${groupids[${x}]}")
        echo $users
done

输出只是空行。

【问题讨论】:

  • 在 SQL 中执行所有这些操作,而不是将第一个查询结果传输到 Bash 数组中。这可以通过单个 SQL 查询来完成,其中包含 groups 表本身的内部连接。

标签: arrays bash psql


【解决方案1】:

好点了吗?

#!/bin/bash
IFS=$'\n' read -r -d '' -a groupids < <(psql -X -A -d files -t -c 'select id from groups where parent=127')

for gid in "${groupids[@]}"
do
    # check that we're dealing with digits
    [[ $gid =~ ^[[:digit:]]+$ ]] || { echo "invalid format: $gid" >&2; continue; }

    users=$(psql -X -A -d files -t -c "select id from groups where parent=$gid")
    echo "$users"
done

【讨论】:

  • 为什么将 groupids 转移到 bash 数组中,而不是从 groups 表本身执行 sql 内连接?
  • 喜欢这个? select id from groups g1 inner join groups g2 on g2.id = 127 and g1.parent = g2.id 但他所做的更像是:select id from groups where parent in ( select id from groups where parent = 127)
  • 看起来不错
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-07
相关资源
最近更新 更多