具有条件的单独列

时间:2015-02-19 07:19:30

标签: mysql sql sql-update

我有一张包含一些问题数据的表格。例如,表格如下:

ID   NAME                            JOB
---  ---------------------------     ---------------
1    Peter                           Teacher
2    John                            Programmer
3    Tom**He is a Teacher  
4    Alan**He is a Accountant

问题是某些数据已正确插入但有些数据尚未正确插入。现在我想执行一个SQL,以使表格如下所示:

ID   NAME                            JOB
---  ---------------------------     ---------------
1    Peter                           Teacher
2    John                            Programmer
3    Tom                             Teacher  
4    Alan                            Accountant

我不熟悉SQL语句所以我可以考虑使用以下PHP脚本来解决这个问题。

$sql1 = "SELECT NAME FROM MY_TABLE WHERE JOB = '' AND NAME LIKE '%He is a %'";
$res1 = mysql_query($sql1);
while($row1 = mysql_fetch_array($res1)){
    $new_data = explode("**He is a ", $row1["NAME"]);
    $sql2 = "UPDATE MY_TABLE SET NAME = '".$data[0]."', JOB = '".$data[1]."' WHERE ID = '".$data["ID"]."'";
    mysql_query($sql2);
}

有人能建议我用一个或几个SQL语句修复此问题的更好方法吗?感谢

2 个答案:

答案 0 :(得分:2)

UPDATE 
SET    NAME     = SUBSTRING_INDEX(SUBSTRING_INDEX(NAME, '**He is a ', 1), ' ', -1),
       job      = SUBSTRING_INDEX(SUBSTRING_INDEX(NAME, '**He is a ', 2), ' ', -1)
WHERE  NAME LIKE '%**He is a %'

答案 1 :(得分:1)

您可以使用substring_index函数拆分字符串,并在单个update语句中应用所有更改:

UPDATE my_table
SET    JOB = SUBSTRING_INDEX (name, '**He is a ', -1),
       name = SUBSTRING_INDEX (name, '**He is a ', 1),
WHERE  name LIKE '%**He is a %' AND
       (job IS NULL OR job = '') -- Just to be on the safe side