0

I have a database in phpmyadmin for all my suppliers. I have created a php file that exports to csv on a daily basis the cheapest stock and quantity of each unique sku in the database. At the moment however, it is excluding any item that has no stock anywhere, however, i would like that... if there is no stock anywhere to print 0 for those items.

The original sql statement is (where name=SKU):

SELECT name,MIN(price) AS minPrice,quantity FROM products WHERE quantity > 0 GROUP BY name

I tried already the following, but this does not work as intended:

SELECT name,MIN(price) AS minPrice,IF(quantity > 0,quantity,'0') AS quantity FROM products GROUP BY name
4

2 回答 2

0

你想要条件聚合:

SELECT name, MIN(price) AS minPrice, coalesce(sum(quantity), 0) AS quantity 
FROM products
GROUP BY name;

您的查询的问题是where过滤掉所有产品 where quantityis的子句0。你似乎真的想要这些。

我已经包括了以防coalesce()万一。您的实际数据可能不需要它。quantityNULL

于 2013-08-16T10:57:27.203 回答
0

如果您正在寻找价格最低的产品数量,请尝试:

SELECT  name
,       price
,       coalesce(quantity,0) as quantity
FROM    products p1
WHERE   price = 
        (
        SELECT  min(price)
        FROM    products p2
        WHERE   p1.name = p2.name
        )
于 2013-08-16T10:58:47.770 回答