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
https://forums.phpfreaks.com/topic/268211-normalize-database-populate-map-table/
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

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.