如何使用SQLite正确执行CREATE INDEX

时间:2012-03-23 17:40:59

标签: mysql sqlite indexing

我正在尝试将我的MySQL create table语句转换为SQLite create table语句。大部分我已经完成了,但是我不知道如何将MySQL的UNIQUE INDEX更改为Sqlites CREATE INDEX(我认为这些大致相同,如果我错了请纠正我)。

所以我有以下MySQL表(它改为:

-- -----------------------------------------------------
-- Table `pyMS`.`feature`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `pyMS`.`feature` (
  `feature_id` VARCHAR(40) NOT NULL ,
  `intensity` DOUBLE NOT NULL ,
  `overallquality` DOUBLE NOT NULL ,
  `quality` DOUBLE NOT NULL ,
  `charge` INT NOT NULL ,
  `content` VARCHAR(45) NOT NULL ,
  `msrun_msrun_id` INT NOT NULL ,
  PRIMARY KEY (`feature_id`, `msrun_msrun_id`) ,
  UNIQUE INDEX `id_UNIQUE` (`feature_id` ASC) ,
  INDEX `fk_feature_msrun1` (`msrun_msrun_id` ASC) ,
  CONSTRAINT `fk_feature_msrun1`
    FOREIGN KEY (`msrun_msrun_id` )
    REFERENCES `pyMS`.`msrun` (`msrun_id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

我根据http://www.sqlite.org/lang_createindex.html更改了索引。我也改变了从MySQL到SQLite的其他一些东西,但我测试了它们并且它们有效。 所以这是我的SQLite代码:

-- -----------------------------------------------------
-- Table `feature`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `feature` (
  `feature_id` VARCHAR(40) NOT NULL ,
  `intensity` DOUBLE NOT NULL ,
  `overallquality` DOUBLE NOT NULL ,
  `quality` DOUBLE NOT NULL ,
  `charge` INT NOT NULL ,
  `content` VARCHAR(45) NOT NULL ,
  `msrun_msrun_id` INT NOT NULL ,
  CREATE UNIQUE INDEX `id_UNIQUE` ON `feature` (`feature_id` ASC) ,
  CREATE INDEX `fk_feature_msrun1` ON `msrun` (`msrun_msrun_id` ASC) ,
  CONSTRAINT `fk_feature_msrun1`
    FOREIGN KEY (`msrun_msrun_id` )
    REFERENCES `msrun` (`msrun_id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION);

这不起作用。当我删除I​​NDEX线时,它确实有效。据我所知,INDEX行符合此描述http://www.sqlite.org/lang_createindex.html,我看不出它出错的地方。那么如何更改两行

CREATE UNIQUE INDEX `id_UNIQUE` ON `feature` (`feature_id` ASC) ,
CREATE INDEX `fk_feature_msrun1` ON `msrun` (`msrun_msrun_id` ASC) ,

使他们的语法正确吗?

2 个答案:

答案 0 :(得分:45)

CREATE UNIQUE INDEX是它自己的声明,不能在CREATE TABLE声明中使用。

将索引语句移出CREATE TABLE

CREATE  TABLE IF NOT EXISTS `feature` (
  `feature_id` VARCHAR(40) NOT NULL ,
  `intensity` DOUBLE NOT NULL ,
  `overallquality` DOUBLE NOT NULL ,
  `quality` DOUBLE NOT NULL ,
  `charge` INT NOT NULL ,
  `content` VARCHAR(45) NOT NULL ,
  `msrun_msrun_id` INT NOT NULL,
  CONSTRAINT `fk_feature_msrun1`
    FOREIGN KEY (`msrun_msrun_id` )
    REFERENCES `msrun` (`msrun_id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION);
CREATE UNIQUE INDEX `id_UNIQUE` ON `feature` (`feature_id` ASC);
CREATE INDEX `fk_feature_msrun1` ON `feature` (`msrun_msrun_id` ASC);

答案 1 :(得分:12)

您需要查看CREATE TABLE语法,而不是CREATE INDEX。 SQLite将在CREATE TABLE语句中接受这种形式的UNIQUE约束。

CREATE  TABLE IF NOT EXISTS `feature` (
...
  CONSTRAINT `id_UNIQUE` UNIQUE (`feature_id`),
...
);