我有一个查询,其中选择了所有销售的产品。我想要做的是反转查询并在一段时间内获得所有未售出的产品。
这是对一段时间内销售的所有产品的查询。
SELECT
product.product_id,
product.product_brand_id,
product.product_model_id,
product.product_subcategory_id,
product.product_retail_price,
product.product_wholesale_price,
product.product_aretail_price,
product.product_awholesale_price,
product.product_oretail_price,
product.product_owholesale_price,
product.product_quoted_price,
product.product_aquoted_price,
product.product_dquoted_price,
product_sold.product_type, SUM(product_sold.product_quantity) AS product_quantity_sold, SUM(product_sold.product_total_price) AS total_price_sold
FROM product
INNER JOIN product_sold
ON product.product_id = product_sold.product_id
AND product.product_subcategory_id = '$subcategory_id'
INNER JOIN sales
ON sales.sales_id = product_sold.product_sales_id
WHERE sales.sales_approved = '1'
AND sales.sales_approved_time > '$start_timestamp'
AND sales.sales_approved_time < '$end_timestamp'
GROUP BY product_sold.product_type, product.product_id
ORDER BY SUM(product_sold.product_quantity) DESC
有人可以指导我如何获得未售出的产品,我在这里没有任何想法。感谢。
解答:
SELECT
p.product_id,
p.product_brand_id,
p.product_model_id,
p.product_subcategory_id,
p.product_retail_price,
p.product_wholesale_price,
p.product_aretail_price,
p.product_awholesale_price,
p.product_oretail_price,
p.product_owholesale_price,
p.product_quoted_price,
p.product_aquoted_price,
p.product_dquoted_price,
pq.product_stock_type
FROM
product p
LEFT JOIN
product_sold ps
ON
p.product_id = ps.product_id
INNER JOIN
product_stock pq
ON
p.product_id = pq.product_id
AND
pq.product_quantity > 0
WHERE
p.product_subcategory_id = '$subcategory_id'
AND
ps.product_id IS NULL
答案 0 :(得分:1)
通常,获取未包含在集合B中的集合A的成员的方法是使用左连接。我将从简化您的查询开始:
SELECT p.product_id, ps.product_id from product p
LEFT JOIN product_sold ps
WHERE ps.product_id IS NULL
这将返回product_sold中没有值的所有产品记录。您应该可以从那里添加详细信息。
答案 1 :(得分:0)
试试这个:
SELECT
product.product_id
FROM product
LEFT JOIN
(
SELECT
product.product_id
FROM product
INNER JOIN product_sold
ON product.product_id = product_sold.product_id
AND product.product_subcategory_id = '$subcategory_id'
INNER JOIN sales
ON sales.sales_id = product_sold.product_sales_id
WHERE sales.sales_approved = '1'
AND sales.sales_approved_time > '$start_timestamp'
AND sales.sales_approved_time < '$end_timestamp'
GROUP BY product_sold.product_type, product.product_id
) AS psold
ON product.product_id = psold.product_id
WHERE psold.product_id IS NULL
这样,您有一个已售出产品的子请求,并且您将其与所有产品一起加入,WHERE子句仅选择第一个表中的产品(所有产品)而不选择第二个(已售出产品)中的产品。