Best unofficial Apache Server developers community
Username
Forgot password?
Sign in with Twitter account
Sign in with Facebook account

Sql to get tags in linking table

0

55 views

I have a query that I made to return all the tags in a set with the tags in a concatenated list, but I'm trying to determine how to write a query that will return the same results but only for those items with a specific tag.. list talks by tag, if you will. Logically, if I add a 'where tbl_tag.tag_id=3', it only lists that specific tag in the group.. I want it to be able to still list all of them. Possibly multiple queries are the answer but I'm curious if it can be done with one.

SELECT tbl_talks.*,
       GROUP_CONCAT(tbl_tag.tag_name ORDER BY tbl_tag.tag_name) AS tags
FROM tbl_talks
    LEFT JOIN tbl_linking_talk_tag
        ON tbl_talks.talk_id = tbl_linking_talk_tag.talk_id
    LEFT JOIN tbl_tag
        ON tbl_linking_talk_tag.tag_id = tbl_tag.tag_id
GROUP BY tbl_talks.talk_id

asked February 13, 2011 12:03 pm CST
posted via StackOverflow

1 Answers

0
 

The quick, *****1ish solution would be to wrap your entire query in an outer query, and only return records containing the appropriate tag using WHERE tags LIKE '%....%. This is fragile, because there's always the chance that you'll have one tag (e.g. "berry") that is container within another (e.g. "strawberry"). There are ways around this, but they're not pretty and not very SQLish.

A slightly more correct (and equally untested!) solution would be to add the original query as a subquery in your WHERE clause:

WHERE EXISTS
(
  SELECT
    1
  FROM
    tbl_talks
    LEFT JOIN tbl_linking_talk_tag
      ON tbl_talks.talk_id = tbl_linking_talk_tag.talk_id
    LEFT JOIN tbl_tag
      ON tbl_linking_talk_tag.tag_id = tbl_tag.tag_id
  WHERE
    tbl_tag.tag_id IN (the, tag_ids, you, want)
)

There might be a simpler built-in way of doing this in MySQL, but I don't know it.

answered February 14, 2011 4:46 pm CST

Your answer

Join with account you already have


Sign in with Twitter account
Sign in with Facebook account
Sign in with Google Friend Connect

Preview
Similar questions
Regex to get the tags
January 14, 2011
Search domains by tags?
January 21, 2011
Eliminate html tags
February 2, 2011