【问题标题】:Can this Postgresql table be converted to a MySql table?这个 Postgresql 表可以转换成 MySql 表吗?
【发布时间】:2011-01-09 05:29:35
【问题描述】:

给定一个 Postgresql 表架构:

create table thing (
    id serial primary key,
    key text,
    type int references thing,   
    latest_revision int default 1,
    created timestamp default(current_timestamp at time zone 'utc'),
    last_modified timestamp default(current_timestamp at time zone 'utc')
);
$for name in ['key', 'type', 'latest_revision', 'last_modified', 'created']:
    create index thing_${name}_idx ON thing($name);

有两行我不明白,我想知道是否可以将它们转换为 MySql 表模式?以下行是否可以转换为 MySql 可以理解的内容,因为它似乎在引用自己:

type int references thing,

另外,最后一行是否有一个 MySql 等效项:

$for name in ['key', 'type', 'latest_revision', 'last_modified', 'created']:
    create index thing_${name}_idx ON thing($name);

【问题讨论】:

    标签: mysql postgresql foreign-keys database-schema


    【解决方案1】:

    最后一行看起来像 python,这让我相信这是来自pgloader,一个常用的 python 程序。或者一个临时的 python 程序。这不是 pg 或 psql 中的有效语法 AFAIK。

    references foo, 位是表 foo 主键的外键。如果没有指定列,则默认为主键。

    查看create table 上的文档了解更多信息。

    【讨论】:

    • MySQL 不支持隐式列作为外键的目标。 MySQL 也不支持列级外键声明;您必须在表级别执行此操作。
    • 您在列声明之外的CREATE TABLE 中添加它,但它仍然附加到列并且是列约束,而不是表约束。
    【解决方案2】:

    references 行是一个外键,你可以在 MySQL 中这样使用:

    CREATE TABLE thing (
       ...
       type int,
       FOREIGN KEY (type) REFERENCES thing (id),
       ...
    );
    

    最后两行不是 SQL,它是一些脚本语言。它只是在提到的列上创建索引:

    CREATE INDEX thing_key_idx ON thing (key);
    CREATE INDEX thing_type_idx ON thing (type);
    ...
    

    【讨论】:

      【解决方案3】:

      所以,据你们所说,这将是原始 Postgresql 表的等效 MySql 表模式:

      --
      -- Table structure for table `thing`
      --
      CREATE TABLE IF NOT EXISTS `thing` (
        `id` int NOT NULL auto_increment,
        `key` text,
        `type` int,
        `latest_revision` tinyint NOT NULL default '1',
        `created` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        `last_modified` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        PRIMARY KEY  (`id`)
      ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
      -- 
      -- Constraints for table `thing`
      -- 
      ALTER TABLE `thing`
        ADD CONSTRAINT `thing_ibfk_1` FOREIGN KEY (`type`) REFERENCES `thing` (`id`);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-05
        • 1970-01-01
        • 1970-01-01
        • 2016-06-08
        • 2014-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多