0

私はこのようなテーブルを持っていました:

post:
+----------------+-----------+
| article_id     | tags      | 
+----------------+-----------+
| 1              |  x1,x2,x3| 
| 2              |  x1,x4,x5 | 
+----------------+-----------+

私がやろうとしているのはそれを正規化することなので、さらに2つのテーブルを作成します:

tags:
+----------------+-----------+
| tag_id         | tag_name  | 
+----------------+-----------+
| 1              |    x1     | 
| 2              |    x2     | 
| 3              |    x3     |
+----------------+-----------+

post_tag:
+----------------+-----------+
| id_post         | id_tag  | 
+----------------+-----------+
| 1              |    1     | 
| 1              |    2     | 
| 2              |    1     |
+----------------+-----------+

すべてのタグを post テーブルから tags テーブルにエクスポートし、各タグに独自の ID がタグ テーブルに含まれるようになりましたが、post_tag テーブルでそれを行う方法を考えていると、とても混乱しますか?

編集: questin は、post_tag テーブルにデータを入力する方法です。クエリはどのようになりますか?

このようにしてみました

$sql=mysql_query("SELECT * FROM post"); 
    while($row=mysql_fetch_array($sql)) {
        $article_id=$row['article_id'];
  $all_tags =$row['tags'];      
  $tags= explode(",",$all_tags);                                
    foreach($all_tags as $tag) {
     $sql2=mysql_query("SELECT * FROM tags WHERE tag_name = '$tag'");
      while($row=mysql_fetch_array($sql2)) {                               $tag_id=$row['tag_id'];                                  $q = "INSERT INTO post_tag (id_post, id_tag) VALUE ('$article_id', $tag_id')";
        $r = mysql_query($q);
      }
    }
}

しかし、それは完全な post_tag テーブルを書きません

4

4 に答える 4

1

なるほど、1 つの sql-query で問題を解決したいのですが、便利ではありません。php-power を使用してみてください。成功するでしょう。

phpのやり方。1.テーブルtagsを作成し、 posts_tags(質問で説明したように)。2. PHP で、現在のpostテーブルからすべての行を取得してループします。

foreach($query_results as $row) {
  $article_id = $row['article_id];
  $tags = explode('|', $row['tags']);
  foreach($tags as $tag) {
    // here check if this tag exists in your new `tags` table (by tag's name). If it is, save its id in $tag_id variable.
    // if a tag don't exists then insert it. And put its new id (mysql returns it after inserting) into $tag_id.
    // After that add a row ($article_id, $tag_id) to table `posts_tags`
  }
}

次にtags、古いpostテーブルから列を削除します。利益!

ps テーブル内のタグの名前とtagsテーブル内のペア (article_id、tag_id) に一意のインデックスを作成しposts_tagsます。

于 2012-09-10T12:58:25.953 に答える
1

投稿に含まれるタグごとに、post_tag テーブルにエントリを挿入します。これを m 対 n の関係と呼びます。グーグル;)

  • post_id: 1、tag_id: 1
  • post_id: 1、tag_id: 2
  • post_id: 1、tag_id: 3

役職

  • post_id

鬼ごっこ

  • tag_id
  • タグ名

post_tag

  • post_id
  • tag_id
于 2012-09-07T13:13:54.653 に答える
0

という投稿my cat!があり、その ID が であるとし1ます。catsタグを追加したいと思いますhome

タグがまだ存在しない場合は、最初にタグcatsを作成し、タグ テーブルに作成する必要があります。home彼らがcats | 2andであるとしましょうhome | 4(数字は彼らのIDです)。

1 | 2次に、値と をpost_tag テーブルに保存する必要があります1 | 4。最初の値は投稿の ID、2 番目の値はタグの ID です。

投稿番号 1 のタグを見つけるには、次のようなものが必要です。

SELECT Tags.name FROM Tags, Tags_Posts WHERE Tags_Posts.post_id = 1 AND Tags.id = Tags_Posts.tag_id

于 2012-09-07T13:22:10.210 に答える