MySQL查询更新表A基于表B中的逻辑测试

时间:2017-03-07 20:17:54

标签: mysql sql

我想编写一个MySQL查询,根据表B中的逻辑测试更新表A.

我想只显示[可见:是]带折扣的产品> 40%

折扣逻辑测试:[100 /(old_price / price)]> 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

3 个答案:

答案 0 :(得分:1)

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));

答案 1 :(得分:0)

这可能会给你想要的东西:

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语句。

答案 2 :(得分:0)

这是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