我有2张桌子,上面有来自两个不同卖家的库存。 如果我不能从这两个卖方中的任何一个采购产品,那么我想将另一个表中的值设置为“ 0”。
首先,我从结合UNION的两个卖方库存表中获得一些必需的值
(SELECT A.`id`, B.`product_id`, A.`internal_id`, CASE WHEN A.`in_stock` = 'Stock available' THEN '1' ELSE '0' END as `in_stock` FROM `pricing_dm` A LEFT JOIN `pricing_vendor_mapping` B ON A.`internal_id`= B.`internal_id` WHERE B.`vendor_id` = '1' AND B.`product_id` > '0'
UNION
SELECT A.`id`, B.`product_id`, A.`internal_id`, CASE WHEN A.`in_stock` = 'In Stock' THEN '1' ELSE '0' END as `in_stock` FROM `pricing_m` A LEFT JOIN `pricing_vendor_mapping` B ON A.`internal_id`= B.`internal_id` WHERE B.`vendor_id` = '2' AND B.`product_id` > '0') t1
如果我得到两个卖方的in_stock = 0的结果,那么我想用0更新另一个字段
id product_id internal_id in_stock
1 123 5555 0
1 123 4567 0
如果我可以从一个卖家(如下所示)或两个卖家那里采购产品,那么我什么都不想做。
id product_id internal_id in_stock
1 123 5555 0
1 123 4567 1
基本上,我如何检查product_id的所有结果是否均为'in_stock = 0',并以此为基础更新另一个表。
谢谢
答案 0 :(得分:0)
如果可以联接表,则有更简单的方法来执行此操作,但是您可以获得最大的in_stock数量,并且知道如果它大于0,则可以使用这样的CTE进行此操作(我无法在mysql,因此可能需要一些语法更正)
WITH CTE (in_stock) AS (
SELECT MAX(in_stock) from (
(SELECT A.`id`, B.`product_id`, A.`internal_id`, CASE WHEN A.`in_stock` = 'Stock available' THEN '1' ELSE '0' END as `in_stock` FROM `pricing_dm` A LEFT JOIN `pricing_vendor_mapping` B ON A.`internal_id`= B.`internal_id` WHERE B.`vendor_id` = '1' AND B.`product_id` > '0'
UNION
SELECT A.`id`, B.`product_id`, A.`internal_id`, CASE WHEN A.`in_stock` = 'In Stock' THEN '1' ELSE '0' END as `in_stock` FROM `pricing_m` A LEFT JOIN `pricing_vendor_mapping` B ON A.`internal_id`= B.`internal_id` WHERE B.`vendor_id` = '2' AND B.`product_id` > '0') t1 ))
UPDATE some_table SET some_column = 0
where CTE.in_stock < 1