简体   繁体   English

MySQL查询更新表A基于对表B进行的逻辑测试

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

I want to write a MySQL Query that updates Table A based on logic test made on Table B. 我想编写一个基于对表B进行逻辑测试的更新表A的MySQL查询。

I want to show [visible: yes] only products with discount > 40% 我想显示[可见:是]仅折扣> 40%的产品

Discount logic test: [100/(old_price/price)] > 40 . 折扣逻辑测试:[100 /(原价/价格)]> 40。 The query is for use on PhpMyAdmin (WordPress) 该查询可用于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));

This might give what you want: 这可能会提供您想要的:

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

If it does, substitute the appropriate UPDATE statement for the SELECT statement. 如果是这样,请用适当的UPDATE语句替换SELECT语句。

This is the answer Mr. Dhruv Saxena kindly sent me and works perfectly: 这是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;

He even sent me a demo test: http://rextester.com/OWRQZE95139 他甚至给我发送了演示测试: http : //rextester.com/OWRQZE95139

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM