Search code examples
phpmysqlselectinsertcalculus

Update column if calculation on two other select is greater than


Well, that's hell of a question.

Here is in a way what I would like

$result = mysql_query(" SELECT (less, more) FROM tempTable WHERE id = '$id' ");
    $row = mysql_fetch_row($result);

    if( ($row[1] - $row[0]) / 75  <= 1.5 )
    {
        INSERT INTO tempTable (payValue) VALUES ('$ammount') WHERE id = '$user';        
    }

Question is, is it possible to make one of these two queries?


Solution

  • Yes, you can do this in one statement:

    INSERT INTO tempTable (payValue)
        SELECT $ammount
        FROM tempTable
        WHERE id = '$id' and (more - less) / 75 <= 1.5;
    

    EDIT:

    Well, this is probably another situation where an insert should really be an update:

    UPDATE tempTable
        set payValue = $ammount
        WHERE id = '$id' and (more - less) / 75 <= 1.5;
    

    Use insert when you want to add new rows. Use update when you want to change the values of existing rows.

    If you do want another row, then it would be something like:

    INSERT INTO tempTable (id, payValue)
        SELECT id, $ammount
        FROM tempTable
        WHERE id = '$id' and (more - less) / 75 <= 1.5;