I’m trying to implement a simple tagging system (messing around in php)…
I use the following sql command to get the required thread, its author and the tags associated with it:
$thread = select_Query("SELECT thread.title, thread.id as t_id,
thread.content, author.username, author.id as a_id,
GROUP_CONCAT(DISTINCT tags.name ORDER BY tags.name DESC SEPARATOR ',') AS tags
FROM thread JOIN thread_tags ON thread.id = thread_tags.thread_id
JOIN tags ON thread_tags.tag_id = tags.id
INNER JOIN author on author.id = thread.author_id
WHERE thread.id = $id", $link);
As you can see, I am using GROUP_CONCAT. This works fine, however when I do this, the tags all appear in one variable and I know I can use $pieces = explode(",", $thread['tags]);
However is there another way of doing this? I am asking this because tags are easy to separate however if it was something more complex (e.g. something that contain the delimiter ,).
My database schema is as follows:
thread: id, content, title, author_id
thread_tags: id, tag_id, thread_id
tags: id, name
Don’t try to squish multiple values into a single cell. This isn’t how SQL was designed to be used and as you correctly point out it can cause problems if your separator appears as one of the values.
Luckily there is a way to solve this by rewriting your query. The solution is to return multiple rows instead of multiple values in a cell. Effectively you are normalizing your result set.
In other words, instead of this:
Do this:
Doing this naïvely can result in duplicating the same values for the other columns, which can be wasting bandwidth unnecessarily if those columns could potentially contain a lot of data. The solution to this is to use two queries.
In other words instead of this:
Do this:
Now your result set is in normal form. Also note that you no longer need to run a DISTINCT operation as your results already are distinct. In fact these two queries much more closely match your original database tables so the queries can be much simpler and it will run faster.