【问题标题】:Is it possible to have table in table (mysql)?是否可以在表(mysql)中有表?
【发布时间】:2013-06-11 03:25:29
【问题描述】:

假设我将music 定义为一个表并给它3 列:albumartisttrack

CREATE TABLE music (
    id int auto_increment primary key,
    album varchar(45) not null,
    artist varchar(30) not null, 
    track int(8)
); 

现在我想要另一个表releasedy,其中包含一列:

'Year' and the table music

我想为此我必须将表 music 中的某些行与表 releasedy 中的 year 绑定到另一个表中。所以我可以知道哪一年包含哪些音乐。如果我没记错的话,我必须用外键来做。我应该如何进行?

【问题讨论】:

  • 为什么不在music 表中添加一列year?你能从一张单独的桌子上得到什么好处?
  • 就像安德斯建议的那样,在您的音乐表中设置一个“年份”列会更有意义。如果您想查找特定年份发布的所有音乐,则只需使用 SELECT * FROM music WHERE year = 2013(或您要查找的任何年份)
  • 这只是一个例子来了解我是否能够做到这一点

标签: mysql sql create-table


【解决方案1】:

您不希望“表中的表”,而是希望在查询中将一个表中的记录与另一个表中的记录进行匹配。您可以在此查询之上创建一个view,然后像使用常规表一样使用该视图。

如你所料,建立一个foreign key relationship,然后是JOIN the two tables

【讨论】:

    【解决方案2】:

    没有“表中的表”,只有表和它们之间的关系。

    releasedy 将有 2 列,musicId 和 year。 musicId 是音乐表的外键。

    加入(如您所说的绑定)这两个:

    SELECT * 
    FROM music m
    INNER JOIN releasedy r ON m.id = r.musicId
    WHERE year = ..
    

    在这个例子中这一切都是多余的,但它说明了你想要的“绑定”。

    【讨论】:

      【解决方案3】:
      class Functions { 
          public function getRows($sql){ 
               $result = mysql_query($sql); 
               while($row = mysql_fetch_assoc($result)){ 
                     $data[] = $row; 
               } 
               return $data; 
          } 
      
          public function getMusicData(){ 
               $data = $this->getRows("SELECT * FROM music"); 
               return base64_encode(serialize($data)); 
          } 
      } 
      
      $func = new Functions(); 
      $music = $func->getMusicData(); 
      $sql = "insert into releasedy (id,Year) values (NULL,'".$music."')";
      mysql_query($sql);
      

      $id = '你需要的身份证'; $read = "select * from releasey where id = ".(int)$id; $data = mysql_query($read); $musics = unserialize(base64_decode($data['Year'])); foreach($musics as $music){ // 做点什么 }

      【讨论】:

      • 请编辑您的答案并解释您的代码为何有效。
      • $id = '你需要的身份证'; $read = "select * from releasey where id = ".(int)$id; $data = mysql_query($read); $musics = unserialize(base64_decode($data['Year'])); foreach($musics as $music){ // 做点什么 }
      猜你喜欢
      • 2012-09-04
      • 1970-01-01
      • 1970-01-01
      • 2011-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多