我有一个SQL查询
SELECT DISTINCT cp.model,cp.quantity AS jumlah ,cp.product_id,cd.name AS category_1,cd.category_id AS id_category_1, cd2.name AS category_2,cd2.category_id AS id_category_2, cd3.name AS category_3,cd3.category_id AS id_category_3
FROM cartproduct cp
LEFT JOIN cartproduct_to_category ctc ON ctc.product_id=cp.product_id
LEFT JOIN cartcategory cc ON cc.category_id=ctc.category_id
LEFT JOIN cartcategory_description cd ON cd.category_id=cc.category_id
LEFT JOIN cartcategory AS cc2 ON (cc.category_id=cc2.parent_id)
LEFT JOIN cartcategory_description cd2 ON cd2.category_id=cc2.category_id
LEFT JOIN cartcategory AS cc3 ON (cc2.category_id=cc3.parent_id)
LEFT JOIN cartcategory_description cd3 ON cd3.category_id=cc3.category_id
WHERE cp.quantity > 0 AND cp.product_id=6
在输出中有很多数据。
来自表cartproduct_to_category的真实数据是
我的问题的解决方案是什么?
答案 0 :(得分:0)
SELECT DISTINCT cp.model,cp.quantity AS jumlah ,cp.product_id,cd.name AS category_1,
cd.category_id AS id_category_1, cd2.name AS category_2,
cd2.category_id AS id_category_2,
cd3.name AS category_3,
cd3.category_id AS id_category_3
FROM cartproduct cp
LEFT JOIN
(
SELECT Distinct product_id FROM cartproduct_to_category
)cartproduct_to_category ctc ON ctc.product_id=cp.product_id
LEFT JOIN cartcategory cc ON cc.category_id=ctc.category_id
LEFT JOIN cartcategory_description cd ON cd.category_id=cc.category_id
LEFT JOIN cartcategory AS cc2 ON (cc.category_id=cc2.parent_id)
LEFT JOIN cartcategory_description cd2 ON cd2.category_id=cc2.category_id
LEFT JOIN cartcategory AS cc3 ON (cc2.category_id=cc3.parent_id)
LEFT JOIN cartcategory_description cd3 ON cd3.category_id=cc3.category_id
WHERE cp.quantity > 0 AND cp.product_id=6
请更改您的查询。
答案 1 :(得分:0)
您正在使用左连接,它会在每个连接的左表中添加行到右表。如果您只需要数据交集,请使用Inner Join。
请注意,你现在正加入3张桌子。