I’m trying to create a efficient query which will retrieve ‘projects’ from a database and all the relevant ‘tags’ which have been assigned to that particular project.
My table setup mimics that of wordpress, and is a tad complicated:
term
- Where I define the tags name, slug etc
term_relationships
- Links the project to a term in the above table.
term_taxonomy
- Defines the taxonomy of each of terms in the term table e.g. 'category', 'tag'.
So, what I need to do is first query the term_taxonomy table for any entries with the taxonomy ‘tag’, then filter these results so that only the terms specified in term_relationships are returned. Finally I then need to query the term table to return the relevant tags.
My question is which is fastest way of doing this? I imagine it would be best to split it into multiple queries eg. Query 1: retrieve project, Query 2: retrieve project tags but please consider I may have up to 20-30 projects per page.
PS: I know it’d be far easier to just create a new table specifically for tagging, but I’d like to confine it to my current setup for now.
Any help would be much appreciated, as this is driving me mad!
note that the
group byclause does not include all selected columns from project – other databases will bitch about this, but Msql won’t. Also note that it is perfectly valid to do so in this case, asp.idis the primary key of project, so there can be only one distinctnamevalue perp.id.One word of caution RE
GROUP_CONCAT():See http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
So decide in advance how large the list of tags may be, and set @@group_concat_max_len to that value.