我需要获取特定列值的数据,但还包括项目
IF
,它们已启用 inventory
并且 stock
大于 0。
以下只是一个概念查询,以直观地表达我的意图。当然不行。
SELECT id, name, image, price
FROM shop
WHERE published = 1
AND price > 2
/*concept clause here*/
IF(inventory = 1 AND stock > 0, include, ignore)
/*end concept*/
ORDER BY RAND()
LIMIT 30
shop
__________________________________________
|id|name |image |price|inventory|stock|
------------------------------------------
|4 |widget|pic.jpg |6 |1 |12 |
------------------------------------------
|5 |bolt |bolt.jpg|7 |0 |0 |
------------------------------------------
|6 |trowel|trow.jpg|12 |1 |0 |
__________________________________________
数组
[
['id'=>4,'name'=>'widget','image'=>'pic.jpg','price'=>6],
['id'=>5,'name'=>'bolt','image'=>'bolt.jpg','price'=>7]
]
启用
inventory
但 stock
值为 0 的行将不位于数组中。
根据这个条件我怎样才能达到效果?
我已经运行了两次类似的查询,然后合并数组
获取未启用库存的物品
SELECT id, name, image, price
FROM shop
WHERE published = 1
AND price > 2
AND inventory = 0
ORDER BY RAND()
LIMIT 30
获取已启用库存且有库存的商品
SELECT id, name, image, price
FROM shop
WHERE published = 1
AND price > 2
AND inventory = 1
AND stock > 0
ORDER BY RAND()
LIMIT 30
合并数组
$merged = array_merge($withoutInventory, $withInventory);
样本数据和预期结果将有助于澄清。我认为你需要将你的列选择括起来并或它们
SELECT id, name, image, price
FROM shop
WHERE (published = 1 AND price > 2) OR
(inventory = 1 AND stock > 0)
ORDER BY RAND()
LIMIT 30