dtmu88600 2013-11-13 16:22
浏览 16
已采纳

PHP SQL在mysql表中的特定记录中添加单词

I need to add 2 different words to a specific field in a table.

table is:

field1, field2 and field3

So first I need to select the records that I want to alter:

SELECT * FROM MyTable where field3 = 1

Suppose the result is 10 records.

I now have 2 variables var1 and var2

I now need to add var1 to 50% of field2 of the table and var2 to the other 50%

How can I do this?

Example:

table:

  id | field2 | field3
-----------------------------
  1    hello      1
  2    hello2     1

String1 String2

Select * from mytable where field3 = 1

Will return 2 fields...

next...

Insert String1 into 50% of result and String2 into the other 50% of result on field2

Output should be:

  id | field2         |  field3
-----------------------------
  1    String1 hello      1
  2    String2 hello2     1
  • 写回答

2条回答 默认 最新

  • duanhao7786 2013-11-13 17:14
    关注

    Get count rows for update.

    select count(*) cnt 
    from MyTable 
    where field3 = 1;
    

    and in php store result to variable $cnt, also make calculation for the middle point between ranges.

    $middle = ceil($cnt/2);
    

    then run following query (of course don't forget to escape a values for variables passed in sql):

    update MyTable a,
          (SELECT @rownum:=0) b
    set field2 = concat(field2, if((@rownum := @rownum+1) > $middle, '$var1', '$var2'))     
    where field3 = 1;
    

    Example below:

    <?php
    
    $conn = mysqli_connect('localhost', 'user', 'pass', 'dbtest');
    $rs = mysqli_query($conn, "select count(*) cnt from MyTable where field3 = 1");
    $row = mysqli_fetch_assoc($rs);
    $cnt = $row['cnt'];
    $middle = ceil($cnt/2);
    $var1 = 'xxx';
    $var2 = 'yyy';
    mysqli_query(
        $conn, 
        "update MyTable a,
               (SELECT @rownum:=0) b
         set field2 = concat(field2, if((@rownum := @rownum+1) > $middle, '$var1', '$var2'))     
         where field3 = 1
        "
    ); 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?