根据列值更新不同表中的不同列

时间:2013-06-06 15:53:30

标签: php mysql

我正在尝试在问题中写的内容,可能是一个愚蠢的问题,但我找不到解决方案,基本上这就是我想做的事情:

if(a.operator_id!=0){
    UPDATE ".$SupportTicketsTable." a ,".$SupportUserTable." b 
    SET a.title=? , a.priority=?, a.ticket_status=?, 
    b.solved_tickets= CASE 
        WHEN a.ticket_status!='0' THEN (b.solved_tickets+1) 
        ELSE b.solved_tickets END , 
    b.assigned_tickets= CASE  
        WHEN a.ticket_status!='0' THEN (b.assigned_tickets-1) 
        ELSE b.assigned_tickets END ,a.ticket_status='0' 
    WHERE a.enc_id=? AND b.id=a.operator_id
}
else{
    UPDATE ".$SupportTicketsTable." a ,".$SupportUserTable." b 
    SET a.title=? , a.priority=?, a.ticket_status=?
        ELSE b.assigned_tickets END ,a.ticket_status='0' 
    WHERE a.enc_id=?
}

a.operator_id=0没有符合条件的b.id值时 有没有办法只在一个查询中执行此操作?提前致谢

1 个答案:

答案 0 :(得分:1)

  1. 我认为你的分支ELSE错了:

    ...
    else{
    UPDATE ".$SupportTicketsTable." a ,".$SupportUserTable." b 
    SET a.title=? , a.priority=?, a.ticket_status=?
        ELSE b.assigned_tickets END ,a.ticket_status='0' 
    WHERE a.enc_id=?
    }
    
  2. 您可以使用dynamicSQL创建一个或两个srored过程,并将表名作为参数放入其中。例如:

    DELIMITER $$
    DROP PROCEDURE IF EXISTS my_proc $$
    CREATE PROCEDURE my_proc (IN SupportTicketsTable VARCHAR(20), IN SupportUserTable VARCHAR(20))
    BEGIN
    SET @SQLS = CONCAT('UPDATE ',SupportTicketsTable, 'a ', SupportUserTable,' b 
        SET a.title=? , a.priority=?, a.ticket_status=?, 
        b.solved_tickets= CASE 
           WHEN a.ticket_status!='0' THEN (b.solved_tickets+1) 
           ELSE b.solved_tickets END , 
        b.assigned_tickets= CASE  
           WHEN a.ticket_status!='0' THEN (b.assigned_tickets-1) 
           ELSE b.assigned_tickets END ,
        a.ticket_status='0' 
        WHERE a.enc_id=? AND b.id=a.operator_id';
    
    PREPARE STMT FROM @SQLS;
    EXECUTE STMT;
    DEALLOCATE PREPARE STMT;
    
    END$$