【问题标题】:SQL attach rows of other tableSQL附加其他表的行
【发布时间】:2018-12-19 09:37:31
【问题描述】:

我有 2 张桌子。名为“places”的主表:

还有一个名为“place_meta”的辅助表:

查询地点时,我想将place_meta 表中具有相同place_id 的行附加到地点结果中。它应该看起来像:

{
    id: 1,
    slug: "test",
    status: "active",
    name: "test",
    excerpt: "blah blah",
    description: "bla blah blah",
    test_url: "https://test.de",
    test2_url: "https://test2.de"
}

或喜欢

{
    id: 1,
    slug: "test",
    status: "active",
    name: "test",
    excerpt: "blah blah",
    description: "bla blah blah",
    meta: {
        test_url: "https://test.de",
        test2_url: "https://test2.de"
    }
}

用 join 尝试过,但真的不知道如何如愿以偿。

【问题讨论】:

  • 您使用的是哪个DBMS 产品? “SQL”只是一种查询语言,而不是特定数据库产品的名称。请为您正在使用的数据库产品添加tag postgresql, oracle, sql-server, db2, ...

标签: mysql sql json join


【解决方案1】:

这适用于两个预定义的元值(test_url 和 test2_url),但如果您有多个元字段,则不是动态解决方案。

SELECT P.*
    ,PM1.meta_value AS 'test_url'
    ,PM2.meta_value AS 'test2_url'
FROM Places P
LEFT JOIN place_meta PM1 ON PM1.place_id = P.id AND PM1.meta_key = 'test_url'
LEFT JOIN place_meta PM2 ON PM2.place_id = P.id AND PM2.meta_key = 'test2_url'
FOR JSON AUTO  

【讨论】:

  • 没有要求只输出问题中的某些键,但似乎要求将结果作为 JSON 字符串返回
  • 感谢 Joakim 的提醒,我在查询中添加了一个 for json 以获得与他的示例 1 相同的输出。我正在阅读 OPs 问题,即他如何从加入的两个表中获取数据一种产生输出的方法。但您可能是对的,他在 SQL 查询和输出格式方面都需要帮助。
  • 我需要一个动态解决方案。如果不可能,那么将所有行也作为集合附加就可以了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-08
  • 2022-01-03
  • 2012-05-18
  • 1970-01-01
  • 2020-08-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多