Need help with complicated UPDATE syntax

Discussion in 'MySQL' started by fdsdfg, Apr 28, 2011.

  1. #1
    Hi all,

    I have a database table called 'AIRULEVAR' which will hold AI rules. The table has the following fields:

    -index
    -ai_id
    -name
    -rule

    The name is inconsequential, the 'ai_id' refers to which AI this rule is for, and the 'index' refers to which rule in sequence this is. For instance, ai_id may have 10 rules with index 1-10.

    The issue is that rules may reference each other. A rule may look like:
    v1 tlb be tgtg 0 is v8
    Code (markup):
    Which is jibberish, but there is a parser that knows what to do with that. However, the 'v1' and 'v8' refer to other rules in this table. Again, the parser can handle this, but my problem lies in populating these:

    Right now, whenever I delete a rule, I run the following command:

    
    DELETE FROM `AIRULEVAR`
       		WHERE `index`=$index
       		AND `ai_id`=$aid
    
    UPDATE `AIRULEVAR`
       		SET
       		    `index` = IF (`index` > $index, `index`-1, `index`)
       		WHERE
       	    ai_id = $aid
    Code (markup):
    This works fine - if $index is 5, it will delete row 5, and move each row 6 or greater down one (so there are no gaps).

    The problem is these rules. If rule 9 contains the text 'v6', then that has to change to 'v5', because the rule that used to be in index 6 is now in index 5.

    The 'vX' can appear anywhere in the rule, and there can be multiple of them. No 'v' will ever be in the rules except for this case.


    Ultimately there are two things I want to change in this code:

    1) If any rule references the rule v$index, it will exit out and say 'no' without performing the delete.
    2) Every rule that references a rule with index > $index should change from v$index to v($index-1).

    PHP runs the SQL commands, so I should probably handle at least the first case in PHP. The second case, however, I would like to do in SQL if possible.

    Thanks for any advice.
     
    fdsdfg, Apr 28, 2011 IP