我需要创建一个记录集,该记录集从另一个表的一行中的一个表中连接3行。
目前我有:
SELECT *
FROM tb_product_sub_cat
LEFT JOIN tb_products ON tb_product_sub_cat.category_id = tb_products.product_subcategory
WHERE tb_product_sub_cat.category_name = %s
我还需要:
tb_product_sub_cat.category_id = tb_products.product_subcategory2 AND
tb_product_sub_cat.category_id = tb_products.product_subcategory3
我需要找到所有产品类别中包含“东西”的产品。
答案 0 :(得分:3)
SELECT * FROM tb_product_sub_cat
INNER JOIN tb_products
ON tb_product_sub_cat.category_id = tb_products.product_subcategory2
AND tb_product_sub_cat.category_id = tb_products.product_subcategory3
AND tb_product_sub_cat.category_id = tb_products.product_subcategory
WHERE tb_product_sub_cat.category_name = %s
这是我对你的场景的解释。如果这对你有用或者你需要详细说明,请告诉我。
修改强>
SELECT * FROM tb_product_sub_cat
LEFT JOIN tb_products
ON tb_product_sub_cat.category_id = tb_products.product_subcategory2
AND tb_product_sub_cat.category_id = tb_products.product_subcategory3
AND tb_product_sub_cat.category_id = tb_products.product_subcategory
WHERE tb_product_sub_cat.category_name = %s
答案 1 :(得分:2)
不完全清楚你想听到什么,但这看起来像UNION的工作: -
SELECT * FROM tb_product_sub_cat LEFT JOIN tb_products ON tb_product_sub_cat.category_id = tb_products.product_subcategory WHERE tb_product_sub_cat.category_name = %s
UNION
SELECT * FROM tb_product_sub_cat LEFT JOIN tb_products ON tb_product_sub_cat.category_id = tb_products.product_subcategory2 WHERE tb_product_sub_cat.category_name = %s
UNION
SELECT * FROM tb_product_sub_cat LEFT JOIN tb_products ON tb_product_sub_cat.category_id = tb_products.product_subcategory3 WHERE tb_product_sub_cat.category_name = %s
答案 2 :(得分:1)
表别名会让您的生活更轻松:
SELECT *
FROM tb_product_sub_cat t
LEFT JOIN tb_products tp ON t.category_id IN (tp.product_subcategory, tp.product_subcategory2, tp.product_subcategory3)
WHERE t.category_name = %s