1

I am not sure if my method is the correct way of doing this in terms of my mysql schema because it is proving difficult as a user could have up to three tags and a post can also have up to three tags.

For example if a post has tags; Music, Technology. And a user has tags Music, Sports. The user would be able to see that post as the tag Music exists in both, the user profile and the post.

My tables are as follows:

Profile has columns:

Profile_id | tag1 | tag2 | tag3

Post has columns:

post_id | author | item | tag1 | tag2 | tag3.

Each tag in the table is related to a specific tag. E.g. tag1= Music, tag2= Sports etc.

A tag is inserted in the table dependant on whether the user ticks it when editing their profile or making a post, so tag could have a value NULL.

4

2 回答 2

2

首先,您需要修复您的设计。创建一个标签表,然后为每个用户和帖子创建一个查找表,这应该使解决方案更加明显。

所以你的新结构将是:

轮廓:

profile_id | Other_Profile_Info ...

邮政:

post_id | author | item 

标签:

tag_id | tag

Post_Tag:

post_id | tag_id

Profile_Tag:

profile_id | tag_id

然后查询可能如下所示:

SELECT p.* FROM Post AS p
   INNER JOIN Post_Tag AS PostTag ON p.post_id = PostTag.post_id
   INNER JOIN Profile_Tag AS ProfileTag ON PostTag.tag_id = ProfileTag.tag_id
   INNER JOIN Profile AS Profile ON Profile.profile_id = ProfileTag.profile_id
WHERE Profile.profile_id = 'MyID'

或使用子查询:

SELECT p.* FROM Post AS p 
WHERE p.post_id IN
   (SELECT post_id FROM Post_Tag WHERE tag_id IN
        (SELECT tag_id from Profile_Tag WHERE profile_id = 'MyID')
   )
于 2013-02-13T17:21:39.813 回答
2

理想情况下,您希望更加规范化您的数据库。创建一个名为Tags并具有列 tag_id 和 tag_name 的新表将比多列提供更好的灵活性。例如,如果您希望帖子有 100 个或更多标签怎么办?

创建一个管理帖子和标签之间关系的新表(即post_tags)以及另一个用于标签和用户的表(user_tags)将使您做得更好。

例如,您可以找到给定用户兴趣的所有帖子:

select p.*
from users u
join user_tags ut on u.user_id = ut.user_id
join post_tags pt on ut.tag_id = pt.tag_id
join posts p on p.id = pt.post_id
where u.user_name = 'theUser'

请记住,您需要两个多对多表来拥有两个 id 的复合键,并检查您的查询是否有可能的重复项等。

于 2013-02-13T17:26:14.973 回答