我想用 3 个关系表进行查询,我想获取 json 格式
product_type (parent)
/ \
product_type Addresses (child)
/
product_brand (grandchild)
我在查询中的关系很好,但出现错误:
#1241 - Operand should contain 1 column(s)
这就是我的查询:
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"
}]
}
]
}]
最佳答案
了解表的数据结构会有所帮助。我是根据您的查询和预期数据猜测的。您的查询向我暗示您的数据没有尽可能地规范化。如果 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
关于mysql - SQL where子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32279796/