Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching records with slug instead of ID

I'm currently trying to find the best way (in term of usability and performance) when dealing with a situation like fetching records tagged with a specific tag, or category, or something like that.

A good way (the way I wanted to do), would be to fetch records with the tag/category slug, so the URL would look like :

http://stackoverflow.com/questions/tagged/language-agnostic

fetching records by slug, which looks better than :

http://stackoverflow.com/questions/tag/789/language-agnostic

fetching by ID and adding the slug behind so it's more search-engine friendly. This one is better performance-wise, because fetching data by an integer ID would be faster than a string. (cmiiw)

Now, with a db schema like :

posts    post_to_tags    tags
-----    ------------    ----
id       id              id
title    post_id         name
content  tag_id          slug
...                      ...

am I doing it right ? Is there pitfall or best-practices that I need to know to avoid performance problems ? (eg. tags should not exceed 10,000 records, or tag slug should not exceed n characters, or something else)

Thanks in advance.

like image 406
andyk Avatar asked Jan 27 '09 08:01

andyk


1 Answers

With the first URL style and your current db design, you can do this:

select ...
from   posts p
join   posts_to_tags pt on pt.post_id = p.post_id
join   tags t on t.id = pt.tag_id
where  t.slug = [url slug value];

As long as tags.slug is indexed, this should be very efficient, hardly any different from

select ...
from   posts p
join   posts_to_tags pt on pt.post_id = p.post_id
where  pt.tag_id = [url tag ID];
like image 147
Tony Andrews Avatar answered Nov 16 '22 04:11

Tony Andrews