我有四个桌子。首先,让我分享他们的结构
子类别
id
name
子类别三
id
name
sub_category_id
产品
id
name
sub_category_three_id
图片
id
image
product_id
现在,我想获得1个sub_category,并在sub_category(id)的基础上获取来自子类别3的所有数据,并在sub_category_three的基础上获取sub_category_three的所有产品,并在产品基础上获取所有图像。
我在三个表上尝试了该查询,但是随后变得很复杂,所以我来到了这里。
SELECT sct.sct_name,sc_name,p.name
FROM sub_categories_three sct
INNER JOIN sub_categories sc
ON sc.id = sct.sub_category_id
INNER JOIN products p
ON sct.id = p.sub_category_three
答案 0 :(得分:1)
这是一个简单的联接查询,用于连接所有表:
select * from sub_category sc inner join
sub_category_three sct on sc.id = sct.sub_category_id inner join
products p on sct.id = p.sub_category_three_id inner join
images i on i.product_id = p.id
where ....
答案 1 :(得分:1)
这是简单的内部联接查询
SELECT * FROM products
INNER JOIN images ON images.product_id = products.id //link images with product id
INNER JOIN sub category three sct ON sct.id = products.subcategory_three_id //link product subcategory three id with sub category three
INNER JOIN sub category sc ON sc.id = sct.sub_category_id //finally link sub category with subcategory three `
如有必要,添加条件
编辑
SELECT * FROM products
INNER JOIN images ON images.product_id = products.id //link images with product id
INNER JOIN sub category three sct ON sct.id = products.subcategory_three_id //link product subcategory three id with sub category three
INNER JOIN sub category sc ON sc.id =
( SELECT id
FROM sub category AS sc
WHERE sc.id = sct.sub_category_id
LIMIT 1
) //finally link sub category with subcategory three `
答案 2 :(得分:0)
您可以使用以下查询,其中包含一些说明:
exp(X)
希望如此,请随时提出更多说明。