【问题标题】:Denoting multi-dimensional array data in relational database table?在关系数据库表中表示多维数组数据?
【发布时间】:2012-07-02 19:08:57
【问题描述】:

假设我有这样一个类似对象的数据记录:

$article = array(
    'title' => '',
    'tagline' => '',
    'content' => '',
    'stats' => array(
        'words' => 0,
        'paragraphs' => 0,
        'tables' => 0
    ),
    'references' => array(
        'reference 1',
        'reference 2',
        'reference 3'
    ),
    'attachments' => array(
        'images' => array(
            'image 1',
            'image s'
        ),
        'videos' => array(
            'video 1',
            'video 2'
        )
    )
);

我的问题是如何将这个数据记录数组存储在关系数据库中?应该如何设计表结构?

我知道我总是可以设置平面字段,例如 stats_words、stats_paragraphs 等,但是还有更多结构化的方法吗?而不是将 JSON 或序列化字符串存储在单个字段中......

谢谢!

【问题讨论】:

    标签: database


    【解决方案1】:

    例如这样:

    article
      ID
      title _
      tagline _
      content ___
      stat_words
      stat_paragraphs
      stat_tables
    
    article_reference
      ID
      article_id -> article
      reference _
    
    article_attachment
      ID
      article_id -> article
      att_type // image or video
      path _
      title _
    

    _ 表示 varchar/text 字段,其他字段为数字)

    或作为 MySQL DDL:

    CREATE TABLE IF NOT EXISTS article (
       id               INT NOT NULL AUTO_INCREMENT,
       title            VARCHAR(255) NOT NULL,
       tagline          VARCHAR(255) NOT NULL,
       content          MEDIUMTEXT NOT NULL,
       stat_words       INT NOT NULL,
       stat_paragraphs  INT NOT NULL,
       stat_tables      INT NOT NULL,
       PRIMARY KEY ( id )
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
    
    CREATE TABLE IF NOT EXISTS article_reference (
       id               INT NOT NULL AUTO_INCREMENT,
       article_id       INT NOT NULL,
       reference        VARCHAR(255) NOT NULL,
       PRIMARY KEY ( id ),
       FOREIGN KEY ( article_id ) REFERENCES article( id )
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
    
    CREATE TABLE IF NOT EXISTS article_attachment (
       id               INT NOT NULL AUTO_INCREMENT,
       article_id       INT NOT NULL,
       att_type         INT NOT NULL,
       path             VARCHAR(255) NOT NULL,
       title            VARCHAR(255) NOT NULL,
       PRIMARY KEY ( id ),
       FOREIGN KEY ( article_id ) REFERENCES article( id )
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
    

    【讨论】:

      猜你喜欢
      • 2012-02-18
      • 1970-01-01
      • 2017-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-20
      • 2022-01-11
      相关资源
      最近更新 更多