根据子查询更新值

时间:2014-07-28 20:48:33

标签: mysql woocommerce

尝试通过查找'_stock'根据meta_value更新'post_id' _sku

   +---------+---------+----------+---------------+
    | meta_id | post_id | meta_key | meta_value    |
    +---------+---------+----------+---------------+
    | 2922    | 161     | _sku     | VISHID-116E   |
    +---------+---------+----------+---------------+
    | 2955    | 162     | _sku     | VISHID-4402   |
    +---------+---------+----------+---------------+
    | 2889    | 160     | _sku     | VISCTL-EPX960 |
    +---------+---------+----------+---------------+
    | 2894    | 160     | _stock   | 1             |
    +---------+---------+----------+---------------+
    | 2927    | 161     | _stock   | 1             |
    +---------+---------+----------+---------------+
    | 2960    | 162     | _stock   | 1             |
    +---------+---------+----------+---------------+

选择功能有效:

SELECT * FROM wp_postmeta 
WHERE meta_key= '_stock' 
AND post_id=(SELECT post_id FROM `wp_postmeta` WHERE meta_value = 'VISHID-116E')

DEMO Fiddle

但是更新查询没有:

UPDATE  wp_postmeta 
SET meta_value= '230'
WHERE meta_key= '_stock' 
AND post_id="(SELECT post_id FROM `wp_postmeta` WHERE meta_value = 'VISHID-116E')"

修改

以下是根据以下建议提出的建议:

UPDATE wp_postmeta,

    (SELECT post_id, qty
    FROM
        (SELECT meta_value as `sku`, post_id as `post_id`
        FROM `wp_postmeta` 
        WHERE meta_key="_sku") as a
    INNER JOIN
        (SELECT qty, part
        FROM `stock`) as b
    ON a.sku=b.part) src

SET wp_postmeta.meta_value=src.qty
WHERE wp_postmeta.meta_key="_stock"
AND wp_postmeta.post_id=src.post_id

对于尝试从另一个表更新库存数量的WooCommerce的开发人员来说,这应该会有所帮助。

3 个答案:

答案 0 :(得分:2)

UPDATE wp_postmeta x
  JOIN wp_postmeta y
    ON y.post_id = x.post_id
   SET x.meta_value = 230
 WHERE x.meta_key= '_stock' 
   AND y.meta_value = 'VISHID-116E'

http://sqlfiddle.com/#!2/d468e/1

答案 1 :(得分:1)

将您的UPDATE查询更改为

以下

使用INNER JOIN

UPDATE  wp_postmeta 
inner join
(SELECT post_id 
             FROM `wp_postmeta` 
             WHERE meta_value = 'VISHID-116E'
) tab on wp_postmeta.post_id = tab.post_id
SET meta_value= '230'
WHERE meta_key= '_stock'

使用SubQuery

UPDATE  wp_postmeta 
SET meta_value= '230'
WHERE meta_key= '_stock' 
AND post_id = (SELECT post_id FROM 
(
select post_id FROM `wp_postmeta` 
WHERE meta_value = 'VISHID-116E'
) tab
)

您发布的修改后的小提琴http://sqlfiddle.com/#!2/a929af/1

答案 2 :(得分:0)

在尝试更新时,Mysql有点迟钝,如果你不使用连接,你必须以复杂的方式进行。

UPDATE  wp_postmeta 
SET meta_value= '230'
WHERE meta_key= '_stock' 
AND post_id=(SELECT post_id FROM(SELECT post_id FROM `wp_postmeta` WHERE meta_value = 'VISHID-116E')x)

Fiddle