【问题标题】:Merging column returned by inner join in sql在sql中合并内部连接返回的列
【发布时间】:2020-03-12 07:07:51
【问题描述】:

我有两个表兴趣和subint,我想获取与每个兴趣相关的数据,所以我尝试了内连接select interest,subinterest from interest inner join subint on subint.interest_id = interest.id;,结果是

"interest"  "subinterest"
"foodie"    "tea"
"foodie"    "biryani"
"foodie"    "chocolate"
"foodie"    "cookies"
"foodie"    "fast-food"
"cooking"   "cooking"

有什么方法可以格式化我的输出并使其像

"interest"  "subinterest"
"foodie"    "tea"
            "biryani"
            "chocolate"
            "cookies"
            "fast-food"
"cooking"   "cooking"

是否可以通过任何 SQL 查询?或者我需要通过编码来完成。 我想要这个,因为我正在使用 node 和 knex.js 创建一个 API,并且我希望 JSON 格式正确

{
        "interest": "foodie",
        "subinterest": "coffee",
        "subinterest": "tea",
        "subinterest": "biryani"
}

【问题讨论】:

  • 这不是 SQL 的目的。如何格式化结果取决于编码。只有你在 SQL 中要做的,就是按兴趣列排序。

标签: sql json postgresql knex.js


【解决方案1】:

在 Postgres 中构造你想要的 JSON。这会为您提供 每行 的 JSON 记录,这就是我认为您想要的:

select row_to_json(i)
from (select interest, array_agg(subinterest) as subinterests
      from t
      group by interest
     ) i;

Here 是一个 dbfiddle。

【讨论】:

    【解决方案2】:

    您应该尝试构建这样的对象或数组结构:

    arr=[{interest:"foodie",
          subinterest:["tea","biryani","chocolate",
                       "cookies","fast-food"]},    
         {interest:"cooking",
          subinterest:["cooking"]}];
    

    外部 SQL 通过使用一些服务器端代码(如 PHP),然后通过 JSON 字符串传输它以供您的 knex.js 脚本“安全使用”。

    (上面的代码描述了 resulting Javascript 数组,在 JSON 解析之后。)

    【讨论】:

    • 我正在尝试这种方法,但我无法将我的 JSON 转换为您所说的。这是我的 json [ { "interest": "foodie", "subinterest": "coffee" }, { "interest": "foodie", "subinterest": "tea" }, { "interest": "foodie", "subinterest": "biryani" }],如何使用 JS 来实现
    猜你喜欢
    • 2011-06-23
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多