简体   繁体   English

mysql查询用同一表中其他字段的值更新字段

[英]mysql query to update field with the value of other field in the same table

I have a table with these fields: 我有一个包含这些字段的表:

id_post id_post

meta_key meta_key

meta_value meta_value

The query should grab the value of "name_value" where "meta_key" match a given text and remove it from the value of "meta_value" where "meta_key" is "sku". 查询应在“ meta_key”与给定文本匹配的地方获取“ name_value”的值,并将其从“ meta_key”为“ sku”的“ meta_value”的值中删除。

Let say I have these rows: 假设我有这些行:

id_post -- meta_key -- meta_value id_post-meta_key-meta_value

101 -- myCustomText -- train 101-myCustomText-火车

101 -- sku -- cartrain 101- SKU-火车

102 -- myCustomText -- boat 102-myCustomText-船

102 -- sku -- carboat 102-SKU- 汽船

Then after the query is run the results should be: 然后,运行查询后,结果应为:

id_post -- meta_key -- meta_value id_post-meta_key-meta_value

101 -- myCustomText -- train 101-myCustomText-火车

101 -- sku -- car 101-SKU- 汽车

102 -- myCustomText -- boat 102-myCustomText-船

102 -- sku -- car 102-SKU- 汽车

In words the query should do this: 换句话说,查询应该这样做:

FOR EACH ROW WITH THE SAME "id_post" SELECT VALUE OF "meta_value" WHERE " meta_key" == "myCustomText" AND SUSTRACT ITS VALUE FROM "meta_value" WHERE "meta_key" == "sku" 对于具有相同“ id_post”的每行,在“ meta_value”中选择值,在其中“ meta_key” ==“ myCustomText”,并从“ meta_value”中获取其值,在其中“ meta_key” ==“ sku”

Use replace() 使用replace()

update demo
set sku = replace(sku, name_variation, '')

DEMO 演示

Or to show the table as desired view 或者将表格显示为所需视图

select id_post,
name_variation,
replace(sku, name_variation, '') sku
from demo

DEMO 演示

Edit for updated question 编辑更新的问题

use a join with same table but with additional filter on on clause 对同一表使用联接,但对on子句使用附加过滤器

update demo a  
join demo b on (a.id_post = b.id_post and b.meta_key = 'myCustomText' )
set a.meta_value = replace(a.meta_value, b.meta_value, '')
where a.meta_key = 'sku'

Update 更新资料

select *,
replace(a.meta_value, b.meta_value, '') sku
from demo a 
join demo b on (a.id_post = b.id_post and b.meta_key = 'myCustomText' )
where a.meta_key = 'sku'

Select 选择

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

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