【问题标题】:Check Contents of Field before using Concat in MySQL Update Statement在 MySQL 更新语句中使用 Concat 之前检查字段的内容
【发布时间】:2012-01-23 19:01:05
【问题描述】:

我正在使用 Concat 更新数据库中的字段,如下所示

`fieldName`=concat( `FieldName`, ',NEW DATA')

但在某些情况下,我会尝试在字段中创建一个逗号分隔的列表,例如

item 1, item 2, item 3

但除非我事先知道该字段是否为空,否则如果这是该字段中的第一个条目,我无法避免前面有逗号或尾随逗号。

,item 1, item 2...etc 

item 1, item 2, ... etc

有没有一种方法可以在我添加数据之前在 Update 语句中确定字段是否有内容,以避免单独查询数据库?

...或者更好的制作逗号分隔列表的方法!

【问题讨论】:

    标签: mysql sql concatenation


    【解决方案1】:

    是的,像这样使用case 表达式:

    update tableName
    set columnName = 
      case when LENGTH(columnName) > 1
        then select concat(columnName, ',NEW DATA')
        else select 'NEW DATA' end
    

    如果columnName的长度大于1,则columName中有数据可以放逗号,否则只放新数据。

    【讨论】:

    • 谢谢@aF 这看起来很完美,但我遇到了语法错误。试图一次更新几个字段"UPDATE tableName SET mobile='" & mobile & "', invoiceList = case when len(invoiceList) > 1 then concat(invoiceList, '," & currentInvoiceNumber & "') else '" & currentInvoiceNumber & "' end 是相关的sn-p。我不断收到“检查 len 附近的语法(在“
    猜你喜欢
    • 2014-04-18
    • 2013-10-05
    • 2013-01-09
    • 2013-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-17
    相关资源
    最近更新 更多