【问题标题】:Generate a JSON based on SQL query基于 SQL 查询生成 JSON
【发布时间】:2015-04-10 18:56:10
【问题描述】:

您好,我想生成这样的 JSON 输出

{
    "cars": {
        "ferrari": {
           "colors": ["green", "red"]
        },
        "porsche": {
            "colors": ["blue", "yellow"]
        }
    }
}

我有 2 个 Mysql 表:

cars: (id, name) and colors: (id, color, brand_id)

我知道的唯一方法是例如

SELECT * FROM brands
and then...
SELECT * FROM colors WHERE car_id = ? 
to get all the cars colors

仅在一个查询中就可以做到这一点吗?

【问题讨论】:

标签: mysql arrays json


【解决方案1】:

我假设车名就是品牌。你应该做: cars(id, brand), colors(id, color) 和 cars_colors(id_brand, id_color) 然后: SELECT brand, color FROM (cars JOIN cars_colors ON cars.id = cars_colors.id_brand) JOIN colours ON cars_colors.id_color = colors.id;

【讨论】:

  • 该查询将返回多行。看起来我只需要两个,但颜色数据数组被注入到颜色键中。我想避免使用 CODE 这样做。但我不知道是否可能。我尝试使用 CONCAT(),但对于性能来说不是一个好的选择。
  • 如果您使用 PHP,您可以对结果进行循环并执行 $car = $row["brand"]; array_push($carsColors[$car], $row["color"]);然后在数组 $carsColors 上循环以构建您的 JSON。你可以用其他语言做类似的事情。
  • 这是我想要避免的。而且我正在寻求一种仅使用 SQL 来做到这一点的方法。谢谢
猜你喜欢
  • 1970-01-01
  • 2019-01-31
  • 1970-01-01
  • 1970-01-01
  • 2019-11-01
  • 1970-01-01
  • 2018-11-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多