Home  >  Q&A  >  body text

Updates a cell in a specified row and unspecified column with content containing a specific string

<p>I have a table with the following columns: name - course1 - course2 - course3. The two lines look like this: </p> <pre class="brush:php;toolbar:false;">John - physics - math - art Sara - math - chemistry - psychology</pre> <p>Now that John has been kicked out of math class, I want to replace "math" with "none" in his rows. </p> <p>When I looked for a solution, I found this: </p> <pre class="brush:php;toolbar:false;">UPDATE tableName SET `course1` = 'none' WHERE `name`='John' AND `course1`='math';</pre> <p>This might be useful if I knew which column of john "math" was recorded in. But the word can appear in any column. What I need is something like this: </p> <p>sql_query="Find the row where <code>name</code>='John', then find the column where we have the word 'math', just replace 'math' with 'none' there. </p> <p>Can you help me solve this problem? </p>
P粉197639753P粉197639753412 days ago500

reply all(1)I'll reply

  • P粉113938880

    P粉1139388802023-09-05 11:25:34

    In this case, I think there is no other way than to evaluate each column, like this:

    update
       my_table
    set 
       course1 = if(course1 = 'math', 'none', course1),
       course2 = if(course2 = 'math', 'none', course2),
       course3 = if(course3 = 'math', 'none', course3)
    where
       name = 'John';

    reply
    0
  • Cancelreply