Question

I come forth bearing, rather obviously, a brain-stormy question. That, or I'm just too much of a noob to see any obvious answers to it:

How can I achieve a tagging system in which each tag has a specific relationship to each user of a website?

A very plain example of what I'm trying to achieve would be a situation in which the system keeps track of page-hits a user makes for each tag. For example, multiple tag keywords are "tagged" to every page of the website. A page about environmental science might be tagged with keywords like "biology" and "sociology". When User A visits that page, a number is incremented by 1 that counts each time User A has viewed "biology", and another count for "sociology".

Thus, we end up with records that exhibit how much a person likes a particular tag.

What would be the most efficient way to do this with MySQL and would it be possible to work it into a two-table system such as the following?

Table 1: Tags

 - tag_title
 - tagged_pages
 - user_likes

Table 2: Users

 - user_id

Adding more table columns is completely fine. What I'm trying to avoid is duplicating the tags table and all the records in it.

All that I've come up with so far is having the user_likes field be formatted something like this for each tag: 101-12, 99-3, 156-14...etc. Then using PHP explode() to separate the user_id from the number of likes.

Thanks a lot for your creative insight!

Was it helpful?

Solution

Don't ever put more than one information in a column. It's the first rule of normalization and you really shouldn't break it.

I think you need some more tables to correctly build this (and have it normalized correctly)

users
    id
    name

tags
    id
    name

pages
    id

page_tags
    page_id
    tag_id

user_page_hits
    user_id
    page_id
    hits

Now, if you want to know how much a user likes a certain tag, you can create a VIEW on those tables like

user_tag_hits
    as select u.name, t.name, sum(uph.hits) hits from users u
              join user_page_hits uph on uph.user_id = u.id
              join page_tags pt on pt.page_id = uph.page_id
              join tags t on t.id = pt.tag_id
              group by u.name, t.name

Which would produce results like

username tagname  hits
me  tag1    112
me  tag2    112
me  tag3    70
me  tag4    4
me  tag5    4
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top