dongliling6336 2014-01-23 03:05
浏览 128
已采纳

SQL TRIM特定字段(和变量集)中的所有值

Excuse me if I ask the obvious, but I am quite mySQL illiterate .

I am referring to a standard wordpress DB install, although this is not a wordpress specific question, but more mySQL general knowledge ..

If I want to change all the values of a certain field across all posts , I usually do :

UPDATE `wp_postmeta` SET `meta_value` = replace(meta_value, 'old_value', 'new_value') WHERE `meta_key` LIKE 'my_meta_key'

The problem is as follows :

In that specific DB , the INITIAL values were inserted with a white space prefix and suffix , e.g. :

"city name" 

was actually inserted as

" city name "

of course , being a PHP person, I immediately thought of the trim() command - which I found out exists also in mySQL.

SO now I thought I could just do

UPDATE `wp_postmeta` SET `meta_value` = TRIM('meta_value') WHERE `meta_key` LIKE 'my_meta_key'

But It is not working ..

What Am I doing wrong ? I know that mySQL is "ticks sensetive" ( so to speak ) But I tried both 'meta_value' and `meta_value' ( sorry, markdown limitations seems to truncate the backticks)

Doing replace(meta_value, ' ', '') is dengaurous because some cities havea spaces in their name, and LTRIM RTRIM is somewhat not working for me as well

I also know there is a way to set a variable in sql ( @my_var ) but what is the correct syntax of doing that in my case ?

SET @my_var = `meta_value`

and then

UPDATE `wp_postmeta` TRIM(@my_var) WHERE `meta_key` LIKE 'my_meta_key'

I of course know how to fix it in a php loop (with trim() ) but I would like to learn what is the best way to do it in mySQL..

  • 写回答

1条回答 默认 最新

  • drjmrg8766 2014-01-23 03:07
    关注

    To refer to the column, you need backticks:

    UPDATE `wp_postmeta`
        SET `meta_value` = TRIM(`meta_value`)
        WHERE `meta_key` LIKE 'my_meta_key';
    

    Your expression TRIM('meta_value') is trimming the string 'meta_value', not the value in the column.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图