【问题标题】:add values with 'on duplicate key'使用“重复键”添加值
【发布时间】:2011-11-30 22:04:44
【问题描述】:

我有一个名为 $words 的数组

Array
(
[0] => Array
    (
        [token] => dwA
        [pos] => *DII.7,8*
    )

[1] => Array
    (
        [token] => nTr
        [pos] => *DI.5,9*
    )

[2] => Array
    (
        [token] => dwA
        [pos] => *DI.2,8*
    )

[3] => Array
    (
        [token] => nTr
        [pos] => *DI.2,8*
    ))

我想插入以下内容:

foreach ($words as $value)
    {
    $word = $value['token'];
    $attestation = $value['pos'];
    $insert="INSERT INTO Examples (Word, Attestation) VALUES ('$word', '$attestation')

    mysql_query($insert) OR die(mysql_error());
    }

“示例”表有一个名为 ID 的键,具有自动递增功能; 字段词是“唯一的”

我想要的是,在“证明”字段中,每次“单词”相同时都会添加值

所以结果应该如下:

Id    word        Attestation
1     dwA         *DII.7,8*, *DI.2,8*
2     nTr         *DI.5,9*, *DI.2,8*

所以我尝试添加一个“重复键”短语

 foreach ($words as $value)
    {
    $word = $value['token'];
    $attestation = $value['pos'];
    $insert="INSERT INTO Words2 (Word, Attestation) VALUES ('$word', '$attestation')
          on duplicate key update Attestation = 
 ";
    mysql_query($insert) OR die(mysql_error());
    }

但我无法弄清楚我必须在 Attestation = 之后添加什么,以便一个接一个地添加不同的证明,例如:DI.5,9 DI.2,8 还是“重复键”不是正确的方法?

【问题讨论】:

    标签: mysql insert on-duplicate-key


    【解决方案1】:

    试试这个;

    INSERT INTO Words2 (Word, Attestation) VALUES ('$word', '$attestation') 重复密钥更新 Attestation = CONCAT(Attestation, ', ', '$attestation')

    不过,稍后将这些值分开可能有点困难。您可能需要考虑另一个表,以便设置一对多关系。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-13
      • 2019-06-08
      • 2014-08-07
      • 1970-01-01
      • 2019-05-20
      • 1970-01-01
      • 1970-01-01
      • 2014-11-01
      相关资源
      最近更新 更多