Mysql Trigger出现错误

时间:2014-03-05 11:48:02

标签: mysql triggers

我有这个触发器应该这样做:

在条目日志表中创建新条目之前,它将从该表中获取driver_id,将其放入if语句,然后根据结果将新条目中的允许字段设置为Y或No.

    create trigger xxx before insert on entrylog for each row
if  exists (select *
              from driver
              join card_driver
                on driver.id = card_driver.driver_id
              join card
                on card_driver.card_id = card.id
             where driver.id = new.driver_id) then
    set new.allowed = 'Y';
end if

唯一的问题是它有效。如果我尝试将它放入phpmyadmin,我会不断收到此错误:

    Error

SQL query: Documentation

CREATE trigger allowedupdate before INSERT ON entrylog
FOR each
ROW
IF EXISTS (

SELECT *
FROM driver
JOIN card_driver ON driver.id = card_driver.driver_id
JOIN card ON card_driver.card_id = card.id
WHERE driver.id = new.driver_id
)
THEN
SET new.allowed = 'Y';

MySQL said: Documentation
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 9 

if语句取自this并且应该产生相同的结果(只是不回显消息)

$sql ="SELECT *
  FROM driver AS d 
INNER
  JOIN card_driver AS cd
    ON cd.driver_id = d.id
INNER
  JOIN card AS c
    ON c.id = cd.card_id     
 WHERE d.ID = $id";
mysql_select_db('damp');
$result = mysql_query( $sql, $conn );
$row = mysql_fetch_assoc($result);
switch($row['state_id'])
{
case "1":
   echo "<strong><font color=\"green\">Authorisation Granted!</font></strong>";
   break; // This should be a Y , the rest are N
case "2":
   echo "<strong><font color=\"red\">Your card has expired and authorisation is denied</font></strong>";
   break;
case "3":
   echo "<strong><font color=\"red\">Your card has been cancelled and authorisation is denied</font></strong>";
   break;
default:
   echo "<strong><font color=\"red\">The Card ID does not exist</font></strong>";
}

1 个答案:

答案 0 :(得分:0)

这是一个非常微妙的问题,但你错过了最后的end if。它就在那里,但分号结束了触发器的定义。这就是MySQL拥有delimiter关键字的原因。

触发器定义应如下所示:

delimiter $$
create trigger xxx before insert on entrylog for each row
begin
    if  exists (select *
                  from driver
                  join card_driver
                    on driver.id = card_driver.driver_id
                  join card
                    on card_driver.card_id = card.id
                 where driver.id = new.driver_id) then
        set new.allowed = 'Y';
    end if;
end;$$
delimiter ;

我还添加了begin/end。虽然不是绝对必要,但我总是使用它们。而且,如果你的原始语句有它们,你会得到一个编译时错误。