mysql - SQL附加其他表的行

标签 mysql sql json join

我有两张 table 。主表名为“places”:

enter image description here

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

enter image description here

查询地点时,我想将 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"
    }
}

尝试过连接,但真的不知道如何如愿得到它。

最佳答案

这适用于两个预定义的元值(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  

关于mysql - SQL附加其他表的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53848317/

相关文章:

mysql - apache airflow initdb 在 mysql 的 kubernetes_resource_checkingpoint 失败

php - Cookie 在 Chrome 中有效,但在 IE 或 Safari 中无效?

sql - 澄清为什么我们在查询 "expected to retrieve less 2 - 4% of rows in the table"时应该使用 SQL 索引?

json - 将前一个请求中获取的数据传递到下一个 POST 请求 [Swift/SwiftUI]

c# - 使用 LINQ 创建 JSON

php - MySQL - 如何根据用户 ID 合并行并生成 SUM

mysql - 为什么在这种情况下使用 Min 或 Max 会产生不同数量的结果?

php - 如何让zend在sql中设置time_zone

sql - Oracle - 使用联合删除重复行 - 这真的有效吗?

javascript - $sql JSON 正确加载,但即时搜索失败。仅限 JavaScript。