1

我正在尝试创建一个代表配方中的指令的表:

+---------------------+
| recipeId   (PK, FK) |
| stepNumber (PK)     |
|---------------------|
| instruction         |
+---------------------+

这个想法是有一个主键(recipeId, stepNumber)来自recipeIdrecipestepNumber自动增量。

当我尝试创建此表时,出现以下错误:

#1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key 

我正在尝试做的事情是正确的/可能的吗?

4

3 回答 3

3

我的建议是,首先使用 auto_increment 创建通用id列,以便在表中有一个主键。recipeId然后为两者和一起创建一个唯一键,stepNumber这样您就不会有这两个字段的任何重复组合。

为了能够为单个配方添加多个步骤,您需要确保没有recipeIdstepNumber或者instruction设置为自动增量。唯一设置为 auto_increment 的列仍然存在id

所以这两个表的表模式看起来像(忽略category列)

CREATE TABLE `recipies` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL DEFAULT '',
  `category` enum('Salad','Dessert','Meat','Pastry') DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `instructions` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `recipeId` int(11) unsigned NOT NULL,
  `stepNumber` int(11) NOT NULL DEFAULT '1',
  `instruction` text NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `recipeId` (`recipeId`,`stepNumber`),
  CONSTRAINT `instructions_ibfk_1` FOREIGN KEY (`recipeId`) REFERENCES `recipies` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

我们先在recipies表中添加一条记录

INSERT INTO `recipies` (`name`,`category`)
VALUES ('Pumpkin Pie','Pastry');

然后让我们添加一行

INSERT INTO `instructions` (`recipeId`,`instruction`,`stepNumber`)
SELECT
    1,
    'You will need plenty of pumpkins!',
    IFNULL(MAX(`stepNumber`),0)+1
FROM `instructions`
WHERE `recipeId`=1
  • 条件中的1 afterSELECT和 1WHERE都指表id=1中的行recipies
  • IFNULL(MAX(stepNumber),0)+1将为该配方选择最高的步骤编号(如果它不存在,它将选择“0”)+1

如果你想看到它工作,这里有一个SQL fiddle 。

[编辑]
我从来不需要对主键使用组合,但显然在 InnoDB 上进行了以下工作,前提是您在表中还没有主键。

ALTER TABLE `instructions`
ADD PRIMARY KEY(`recipeId`,`stepNumber`)
于 2013-01-20T02:16:48.270 回答
2

I do have to ask - why would you want to? If you think about it, your recipe Id (FK) is going to be unique, then your step number is always going to start from 1 (or zero if you're zero based).

-- edit --

steps table:
recipe_id step_id step_detail
--------- ------- ---------------------------
        1       1 blah
        1       2 blah
        1       3 blah
        2       1 blah
        2       2 blah
        2       3 blah
        2       4 blah
        2       5 blah
--------- ------- ---------------------------

If you included an auto-increment here then the step numbers would just keep on going up instead of resetting to 1 for the next recipe.

-- end edit --

Kind regards, Westie.

于 2013-01-19T23:48:43.093 回答
1

如果这就是你正在使用的,我认为你不能用 InnoDB 做到这一点。显然您可以使用 MyISAM。

http://dev.mysql.com/doc/refman/5.6/en/example-auto-increment.html

于 2013-01-19T21:24:42.830 回答