简体   繁体   English

mysql修改表以添加选定的列

[英]mysql Alter table to add column with selected

I am trying to use ALTER to add a new column (authorID) to the tests table, but I want to have a specific value (which I don't know). 我正在尝试使用ALTER向测试表中添加新列(authorID),但是我想要一个特定的值(我不知道)。

I am trying to run the following, but getting SQL errors. 我正在尝试运行以下命令,但出现SQL错误。 Is this possible, if so where have I gone wrong please? 如果可以,请问我哪里出了错?

SELECT id FROM authors WHERE emailAddress = 'UNASSIGNED' into @unassignedID;
ALTER TABLE Tests ADD COLUMN authorID INT NOT NULL DEFAULT @unassignedID;

Authors table: 作者表:

CREATE TABLE authors
(
  ID INT NOT NULL AUTO_INCREMENT,
  emailAddress VARCHAR(100) NOT NULL UNIQUE,
  regionID INT NOT NULL,
  PRIMARY KEY(ID)
);

Tests Tables: 测试表:

CREATE TABLE Tests
(
  testID INT NOT NULL AUTO_INCREMENT,
  Title VARCHAR(100) DEFAULT NULL, 
  PRIMARY KEY(testID)
);

you can use prepared statement : 您可以使用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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM