我在CodeIgniter模型中使用此数据库查询。

SELECT
                p.product_id,
                p.product_name,
                p.product_photo,
                p.size,
                p.price,
                p.status,
                p.product_image_path
            FROM
                products AS p
            LEFT JOIN
                product_category AS pc
            ON
                p.product_id = pc.product_id
            LEFT JOIN
                vendor_products AS vp
            ON
                vp.product_id = pc.product_id
            WHERE
                pc.category_id = 2
            AND
                vp.vendor_id = 36
            AND
                pc.subcategory_id IN (1,2)
            AND
                pc.subcategory_value_id IN (1,4)


它返回我:



我只需要那些满足sub_category_value_id所有条件的产品。现在,它返回所有条件。

我是数据库新手,对查询并不了解。

最佳答案

下面的查询将根据给定的vendor_id,category_id,subcategory_id和subcategory_value_id为您提供具有product_id和product_name的不同产品。

让我知道这是否适合您!

SELECT
DISTINCT p.product_id,
p.product_name
FROM products AS p
LEFT JOIN product_category AS pc ON p.product_id = pc.product_id
LEFT JOIN vendor_products AS vp ON p.product_id = vp.product_id
LEFT JOIN subcategories AS sc ON sc.subcategory_id = pc.subcategory_id
LEFT JOIN subcategories_value AS scv ON scv.subcategory_value_id = pc.subcategory_value_id
WHERE vp.vendor_id = 2
    AND vp.category_id = 2
    AND pc.subcategory_id IN (1, 2)
    AND scv.subcategory_value_id IN (1, 4)
ORDER BY p.product_id;

08-06 22:46