基于SQL查询生成JSON

时间:2015-04-10 18:56:11

标签: mysql arrays json

您好我想生成像这样的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

只能在一个查询中执行此操作吗?

1 个答案:

答案 0 :(得分:0)

我认为汽车名称是品牌。你应该做: 汽车(id,品牌),颜色(id,颜色)和cars_colors(id_brand,id_color)然后: SELECT品牌,颜色FROM(汽车JOIN cars_colors ON cars.id = cars_colors.id_brand)JOIN颜色ON cars_colors.id_color = colors.id;