Sql where子句

时间:2015-08-28 21:07:47

标签: mysql sql json

我想用3个关系表进行查询,我想得到json格式

product_type (parent)
      /     \
  product_type Addresses (child)
    /
product_brand (grandchild)

我在查询中的关系很好,但是我收到了错误:

  

#1241 - 操作数应包含1列

那是我的疑问:

SELECT *,
   (SELECT *,
     (SELECT *
      FROM product_brand WHERE product_brand.product_type_id = product.product_id) as s
   FROM product WHERE product.product_type_id = product_type.product_type_id) as e
 FROM product_type ;

我需要我的回复看起来像这样:

Data: [{
    product_type_name: "CAT1",
    product_type_details: "",
    product_type_image: "mobileapp/public/images/-98553543.png",
    items: [

        {
            product_name: "SUBCAT2 LAL CAT2",
            product_image: "mobileapp/public/images/",
            product_details: " SD",
            product_price: "",
            items: [{
                product_brand_name: "LAL SUBCAT2 LAL CAT2",
                product_brand_details: " SDSD",
                product_brand_image: "mobileapp/public/images/",
                product_brand_price: "442"
            }, {
                product_brand_name: "DFDF",
                product_brand_details: " DFDF",
                product_brand_image: "mobileapp/public/images/",
                product_brand_price: "13"
            }]
        }
    ]
}]

1 个答案:

答案 0 :(得分:1)

了解表的数据结构会有所帮助。我猜测它基于您的查询和预期的数据。您的查询向我暗示您的数据不是正常化的,也可能是正常的。如果product是product_type的子级,而product_brand是product的子级,则product_brand不需要product_type_id,因为它可以通过关系来确定它。

要回答你的问题,你应该像Rocket建议的那样加入表格。下面是一个嵌套连接查询的示例,它应该返回您想要的结果,假设我对您的表结构的猜测是正确的。

SELECT pt.name, pt.details, pt.image,
    p.name, p.image, p.details, p.price,
    pb.name, pb.details, pb.image, pb.price
FROM product_type AS pt
INNER JOIN product AS p ON p.product_type_id = pt.product_type_id
INNER JOIN product_brand AS pb ON p.product_id = pb.product_id