我目前正在开发一个自定义 cms,用户可以将多个类别分配到单个帖子中。我的问题是:
- 什么是正确的mysql表模式?
 - 您如何将多个选定的类别存储在博客文章表中?
 
如果您有澄清,请告诉我。
你在这里拥有的是多对多的关系。存储关系的标准方法是对类别和帖子使用连接表。该表将只有类别 ID 和帖子 ID。
post 表将没有关于类别本身的信息。
什么是正确的mysql表模式?
一种方法是创建关系表:
CREATE TABLE cms.Posts (
  PostID       SERIAL,
  PostContent  TEXT,
  PRIMARY KEY (PostID)
) Engine=InnoDB;
CREATE TABLE cms.Categories (
  CategoryID   SERIAL,
  CategoryName VARCHAR(20),
  PRIMARY KEY (CategoryID)
) Engine=InnoDB;
CREATE TABLE cms.PostCategories (
  PostID BIGINT UNSIGNED NOT NULL,
  CategoryID BIGINT UNSIGNED NOT NULL,
  PRIMARY KEY (PostID, CategoryID),
  FOREIGN KEY (PostID)     REFERENCES cms.Posts      (PostID),
  FOREIGN KEY (CategoryID) REFERENCES cms.Categories (CategoryID)
) Engine=InnoDB;
您如何将多个选定的类别存储在博客文章表中?
你没有,你将它们存储在PostCategories表中:
$dbh = new PDO('mysql:charset=utf8', $username, $password);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->prepare('INSERT INTO cms.Posts (PostContent) VALUES (?)')
    ->execute([$_POST['content']]);
$qry = $dbh->prepare('
  INSERT INTO cms.PostCategories (PostID, CategoryID) VALUES (?, ?)
');
$qry->bindValue(1, $dbh->lastInsertId());
$qry->bindParam(2, $category);
foreach ($_POST['categories'] as $category) $qry->execute();
每个人(包括我自己)似乎都在使用的解决方案是@rwilliams 所描述的。当查询仅限于单个标签时,这些方法效果很好。要查询 2 个标签(标记为个人和旅行),您需要使用联接。当查询变得更复杂时,这开始崩溃。我认为 MongoDB 将是一个更好的解决方案。
对于多对多关系,您可以将表格设计为
caegory table
    categoryId categorydescription
post table    
    postid     postText
a third table to link them    
    categoryId  postId
    blog_posts
==========
id | 23
title | My title
categories
==========
id | 1
name | yogurt
// another row
id | 2
name | motor cycles
category_blog_post
==================
23 | 2
23 | 1
显示博客文章我的标题被标记为关于酸奶和摩托车的条目