1

我正在制作一个简单的 PHP 论坛,标签是在主题旁边创建的。

该表如下所示:

  CREATE TABLE IF NOT EXISTS `topic` (
  `topic_id ` int(100) NOT NULL AUTO_INCREMENT,
  `topic_head` varchar(5) NOT NULL,
  `topic_body` varchar(20) NOT NULL,
  `topic_tag` varchar(20) NOT NULL,
  `topic_date` varchar(20) NOT NULL,
  `topic_owner` varchar(20) NOT NULL,
  PRIMARY KEY (`topic_id`)
  ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

特别是对于标签,我将以以下形式执行选择查询:

$tags = mysql_query("SELECT DISTINCT topic_tags
                       FROM forum_topics")
                       while($tags = mysql_fetch_assoc($tags){   
                       $split_tags  = "$tags";
                       $pieces = explode(",", $split_tags);

目前,topic_tags 的格式为tag1,tag2,tag3,tag4 我怎样才能让每个主题标签与每个主题相关联?

4

2 回答 2

2

如果我理解正确,你想要的是另一个标签表,然后是第三个表来存储关系。所以:

CREATE TABLE `tags` (
  `t_id` int(11) NOT NULL AUTO_INCREMENT,
  `t_text` varchar(150) NOT NULL,
  `t_datetime` datetime NOT NULL,
  PRIMARY KEY (`t_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

CREATE TABLE `tag_pairs` (
  `tp_id` int(11) NOT NULL AUTO_INCREMENT,
  `tp_topic_id` int(11) NOT NULL,
  `tp_tag_id` int(11) NOT NULL,
  `tp_datetime` datetime NOT NULL,
  PRIMARY KEY (`tp_id`),
  FOREIGN KEY (`tp_topic_id`) REFERENCES topic('topic_id'), 
  FOREIGN KEY (`tp_tag_id`) REFERENCES tags('t_id') 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

然后,根据 ID ($THIS_ID) 获取主题的标签:

$query = mysql_query("
  SELECT tags.t_text 
  FROM tags, tag_pairs, topic 
  WHERE topic.topic_id = '$THIS_ID'
  AND tag_pairs.tp_topic_id = topic.topic_id 
  AND tag_pairs.tp_tag_id = tags.t_id 
 ");
于 2012-09-10T03:37:03.973 回答
0

仅调用列:id, head, body, tag_id (FK),dateuser_id (FK)

这更容易理解,也更容易使用。让我解释:

现在您将列用作:topic_id,但它应该是:topic.id。你怎么得到这个?通过简单地使用tablename + column. 因此,当调用表topics并且您有一个名为 的列id时,您可以通过说来使用它:topics.id。在上面来自 da5id 的答案中,我可以看到他正在使用topics.topic_id,不是有点矫枉过正吗?;)

另外,阅读这篇关于数据库范式 3的文章,并使用database+3nf自己搜索一下

于 2012-09-11T07:42:02.633 回答