我的数据库中有两个longtext类型的值,我想减去它。
这是架构:
我想将_store_price减去0.15并将其存储在_regular_price中以获得此结果:
我对SQL有基本的了解,但我尝试在phpmyadmin中执行此操作而没有任何成功:
UPDATE wp_postmeta AS p1
LEFT JOIN wp_postmeta AS p2
ON p1.post_id = 30860
SET p1.meta_value = CAST( CAST( p2.meta_value as DECIMAL(10,2)) - 0.15 ) as char(20))
WHERE p1.meta_key = '_regular_price'
AND p2.meta_key = '_store_price'
是否有人知道如何实现这一目标?
答案 0 :(得分:1)
您将需要2个查询,因为它们位于2行,您需要“对齐”它们才能在其中一行上执行更新。
UPDATE wp_postmeta AS p1
SET p1.meta_value = (
SELECT CAST((CAST(p2.meta_value AS DECIMAL(10, 2)) - 0.15) AS CHAR(20))
FROM (
SELECT *
FROM wp_postmeta
) AS p2
WHERE p2.post_id = 30860 AND p2.meta_key = '_prix_magasin'
)
WHERE p1.post_id = 30860 AND p1.meta_key = '_regular_price'
;
要更新大量值,请使用内部联接但设置连接条件,以便2个meta_key行现在对齐
UPDATE wp_postmeta AS p1
INNER JOIN wp_postmeta AS p2 ON p1.post_id = p2.post_id
AND p1.meta_key = '_regular_price'
AND p2.meta_key = '_prix_magasin'
SET p1.meta_value = CAST( (CAST( p2.meta_value as DECIMAL(10,2)) - 0.15 ) as char(20))
## example only
## where p1.post_id IN(30860,30861,30862,30863 ...)
;
dbfiddle here
答案 1 :(得分:0)
ON
中的JOIN
条件需要关联两个表中的行。它应该用于指定它们都是相同的post_id
。对每个表本身的条件使用WHERE
子句。
并使用INNER JOIN
除非你需要处理第二张表中没有匹配的情况。
UPDATE wp_postmeta AS p1
JOIN wp_postmeta AS p2 ON p1.post_id = p2.post_id
SET p1.meta_value = p2.meta_value - 0.15
WHERE p1.meta_key = '_regular_price'
AND p2.meta_key = '_store_price'
AND p1.post_id = 30860