簡體   English   中英

MySQL查詢更新表A基於對表B進行的邏輯測試

[英]MySQL Query update Table A based on logic test made on Table B

我想編寫一個基於對表B進行邏輯測試的更新表A的MySQL查詢。

我想顯示[可見:是]僅折扣> 40%的產品

折扣邏輯測試:[100 /(原價/價格)]> 40。 該查詢可用於PhpMyAdmin(WordPress)

Table A (product status)

product_id  visible
1           yes
2           no
3           yes
4           no

Table B (product details)

product_id  meta_key    meta_value
2           price       550
2           old_price   600
1           price       200
1           old_price   400
4           price       300
4           old_price   350
3           price       100
3           old_price   300
update product_status
set visible = 'yes'
where product_id in ( select product_id, (100/(max(old_price)/max(price))) as discount
                        from ( select product_id, meta_value as old_price, null as price
                                 from product_details
                                where meta_key = 'old_price'
                               union
                               select product_id, null, meta_value
                                 from product_details
                                where meta_key = 'price' ) as checkit
                        where (100/(max(old_price)/max(price)) > 40
                        group by product_id));

這可能會提供您想要的:

select product_status.product_id,
case when (1.00*c.meta_value)/(1.00*b.meta_value) < 0.6 then 1 else 0 end as visible
from product_status
inner join
(select * 
from product_details 
where meta_key = 'old_price') b
on product_status.product_id = b.product_id
inner join
(select * 
from product_details 
where meta_key = 'new_price') c
on product_status.product_id = c.product_id

如果是這樣,請用適當的UPDATE語句替換SELECT語句。

這是Dhruv Saxena先生給我的答案,效果很好:

UPDATE product_status ps
INNER JOIN product_details pd1
    ON ps.product_id = pd1.product_id
    AND pd1.meta_key = 'price'
INNER JOIN product_details pd2
    ON ps.product_id = pd2.product_id
    AND pd2.meta_key = 'old_price'

SET ps.visible = 
             CASE
                WHEN (100/(pd2.meta_value/pd1.meta_value)) > 40.00
                    THEN 'yes'
                ELSE
                    'no'
             END;

他甚至給我發送了演示測試: http : //rextester.com/OWRQZE95139

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM