Jump to content

normalize database, populate map table


inTry

Recommended Posts

Hi all,

 

I am trying to normalize my database

 

I had table POST where the all tags have been saved (comma separated):

 

POST:

 

article_id

      all_tags

1

    x1, x2, x3

2

    x2, x3, x4

 

 

now I create new table TAGS and insert all tags from POST table in single column

 

TAGS:

tag_id

    tag_name

1

      x1

2

      x2

3

      x3

 

I made POST_TAG (as map table) table but i have no idea how to populate it,  how the query should look like, how to?

 

POST_TAG:

id_post

      id_tag

1

      1

1

      2

2

      1

 

thank you

 

Link to comment
Share on other sites

$sql=mysql_query("SELECT * FROM post");	
while($row=mysql_fetch_array($sql)) 
	{
		$article_id=$row['article_id'];
		$all_tags=$row['all_tags'];		
		$all_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'];

								echo $tag_id . "<br>";									
								$q = "INSERT INTO post_tag (id_post, id_tag) VALUE ('$article_id', '$tag_id')";
								$r = mysql_query($q);		

								}		
					}
	}

 

I tried something like this, but it doesn't write all post_tag table

Link to comment
Share on other sites

Well, for starters:

 

SELECT
SUBSTRING_INDEX( SUBSTRING_INDEX( post.alltags, ',', 1 ), ',', -1 ) AS tag1
,SUBSTRING_INDEX( SUBSTRING_INDEX( post.alltags, ',', 2 ), ',', -1 ) AS tag2
,SUBSTRING_INDEX( SUBSTRING_INDEX( post.alltags, ',', 3 ), ',', -1 ) AS tag3
FROM post

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.