2

我正在尝试运行以下查询以在 mysql 中创建一个表,但出现错误。

create table newtable ( 
       version_id int(11) auto_increment not null, 
       test_id int(11)   default version_id, 
       primary key(version_id) 
 );

ERROR 1064 (42000): 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 'version_id not null, primary key(version_id), unique key(test_id) )' at line 1

我正在克服错误。

我认为问题在于将 test_id 默认设置为 version_id,因为它可以正常工作。


谢谢巴拉_

-- Update

这是我想做的,

当我创建一个新行时,我想使用 version_id 作为键。当我更新时,我想使用现有记录的值作为键。注意 test_id 不是主键。

4

1 回答 1

2

我认为您不能将“变量”用作默认值。它们可能必须是常数。如果您想获得这种效果,您可能可以在“插入之前”的存储过程/触发器中执行此操作,这样如果未提供 trial_id,它将被分配与 version_id 相同的值......

这是一个教程,可以帮助您实现这一目标。

我认为您的触发器看起来像:

mysql> CREATE TRIGGER myTrigger
    -> BEFORE INSERT ON newtable
    -> FOR EACH ROW
    -> BEGIN
    ->      IF NEW.trial_id IS NULL THEN
    ->         SET NEW.trial_id = NEW.version_id;
    ->      END IF;
    -> END$$
于 2010-07-27T00:25:29.230 回答