3

我有一张桌子,上面有以下内容:

+----+-------+-------+-----------+-----------+--------------+--------------+
| id | stock | price | usedStock | usedPrice | specialStock | specialPrice |
+----+-------+-------+-----------+-----------+--------------+--------------+
| #1 |     1 | 10.00 |         0 | 0         |            0 | 0            |
| #2 |     0 | 0     |         1 | 15.00     |            1 | 20.00        |
| #3 |     0 | 0     |         0 | 11.00     |            1 | 14.00        |
+----+-------+-------+-----------+-----------+--------------+--------------+

如果商品类型有库存,我想创建一个查询,首先按最低价格订购。

因此查询将产生以下顺序:

#1 - 10.00 (because 10.00 is the lowest result)
#3 - 14.00 (because although 11.00 is less, it's not in stock)
#2 - 15.00 (because 15.00 is lower than 20.00)

我已经在这个问题中添加了 PHP 标记,以防在选择表格后使用 PHP 进行更快的计算。

4

3 回答 3

0

我会先创建一个视图

CREATE VIEW stock_min_price AS
SELECT id, LEAST(IF(stock > 0, price, 1000000000),
    IF (usedStock > 0, usedPrice, 10000000000),
    IF (specialStock > 0, specialPrice, 10000000000)) AS actualPrice
FROM tablename;

然后按所有商品的实际价格选择和订购

SELECT id, IF(actualPrice = 1000000000, NULL, actualPrice) AS price
FROM stock_min_price
ORDER BY actualPrice

//编辑:当库存可以大于1时比较> 0

于 2013-02-03T22:52:45.270 回答
0

如果商品有库存,我会以最低价格订购:

ORDER BY
  LEAST(CASE WHEN stock        THEN price        ELSE GREATEST(price, usedPrice, specialPrice) END,
        CASE WHEN usedStock    THEN usedPrice    ELSE GREATEST(price, usedPrice, specialPrice) END,
        CASE WHEN specialStock THEN specialPrice ELSE GREATEST(price, usedPrice, specialPrice) END)

如果条件为真(>=1),每个CASE WHEN都会返回价格,否则返回最大的价格。在这里拉小提琴。

于 2013-02-03T22:58:48.853 回答
0

坦率地说,您应该重新考虑针对这种操作的数据建模。这三种股票之间没有直接联系,因此您确实应该将它们标准化为另一个表。为此,我将假设您的旧表名为oldTable

    CREATE TABLE stock(item_id integer, amount integer, price double, type enum('normal', 'used', 'special'));

    INSERT INTO stock SELECT o.id, o.stock, o.price,'normal' FROM _oldTable as o 
    WHERE o.stock >0 OR o.amount >0 ;

    INSERT INTO stock SELECT o.id, o.usedStock, o.usedPrice, 'used' FROM _oldTable as o
    WHERE o.stock >0 OR o.amount >0 ;

    INSERT INTO stock SELECT o.id, o.specialStock, o.specialPrice,'special' FROM _oldTable as o
    WHERE o.stock >0 OR o.amount >0 ;

你有它。如您所见,您现在基本上可以通过简单join的库存表获取您的信息。

    SELECT o.id, s.kind, min(s.price) FROM _oldTable_ AS o 
    JOIN stock as s ON s.item_id = o.id AND s.amount > 0
    GROUP BY s.item_id

如果你想产生一个像你原来的表一样的输出,你可以使用:

    SELECT o.id, n.amount as amount, n.price as price, u.amount as usedAmount, u.price as usedPrice, s.amount as specialAmount, s.price as specialPrice
    FROM _oldTable_ AS o 
    LEFT JOIN stock as n ON n.item_id = o.id AND n.type = 'normal'
    LEFT JOIN stock as u ON u.item_id = o.id AND n.type = 'used'
    LEFT JOIN stock as s ON s.item_id = o.id AND n.type = 'special';

现在也更容易 a) 获取每个库存的总金额(金额列上的总和,带有GROUP BYitem_id 的声明)b) 获取使用的库存类型。

ps:item_id如果你有很多项目,你可能应该在列上设置一个索引。另请注意,如果并非所有项目都有各种库存,此解决方案可能会为您节省磁盘空间

于 2013-02-04T01:15:15.637 回答