我正在尝试使用ALTER将新列(authorID)添加到测试表中,但我希望有一个特定的值(我不知道)。
我正在尝试运行以下内容,但遇到SQL错误。这是可能的,如果是的话,我哪里出错了?
SELECT id FROM authors WHERE emailAddress = 'UNASSIGNED' into @unassignedID;
ALTER TABLE Tests ADD COLUMN authorID INT NOT NULL DEFAULT @unassignedID;
作者表:
CREATE TABLE authors
(
ID INT NOT NULL AUTO_INCREMENT,
emailAddress VARCHAR(100) NOT NULL UNIQUE,
regionID INT NOT NULL,
PRIMARY KEY(ID)
);
测试表:
CREATE TABLE Tests
(
testID INT NOT NULL AUTO_INCREMENT,
Title VARCHAR(100) DEFAULT NULL,
PRIMARY KEY(testID)
);
答案 0 :(得分:0)
您可以使用prepared
statement
:
SELECT id into @unassignedID FROM authors WHERE emailAddress = 'UNASSIGNED' limit 1;
SET @sql = CONCAT('ALTER TABLE Tests ADD COLUMN authorID INT NOT NULL DEFAULT ',@unassignedID);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;