0

I have a 3 table tag system, topics, tags and tagtopic.

I now want to display the various tags for each topic as I display the topic. Since there are multiple tags for one topic, when I do the query below, I get multiple rows and the topic displays multiple times, once for each row. I don't think I can use a groupby as I'm not doing anything mathematical with the columns. What I really would like would be for each topic, display the topic and then a list of tags for a post such as (for Siri), 'iphone,smartphone,Siri'. tables:

topics
id | name |userid
tags
id | topicid | topicname
tagtopic
id | tagid | topicid '

$sql = "SELECT * FROM `topics` t
LEFT JOIN `tagtopic` tagtopic
on t.id = tagtopic.topicid
WHERE t.id= '12'";

Should mention that display is done with while($row = mysql_fetch_array($res)) so that it is displaying the rows of the recordset. I would like it to display the topic once, but since there are multiple rows created for the tags, it is displaying multiple times.

Do I have to give up on the join and do a subquery? Thanks for any suggestions.

2
  • please post tables structures. Commented Jun 1, 2012 at 13:55
  • Should tags.topicname instead be called tags.tagname? Commented Jun 1, 2012 at 14:18

2 Answers 2

2

You can do a GROUP_CONCAT which will put all the tags into a single field separated by a comma.

SELECT GROUP_CONCAT(tt.tagid) FROM topics t
JOIN tagtopic tt ON tt.topicid = t.topicid
WHERE t.id=12
GROUP BY t.id
Sign up to request clarification or add additional context in comments.

Comments

0

If you execute this query for ON AND ONLY ON topic ( deducted by WHERE t.id = 12 )
In your while loop :

var first = true;
while($row = mysql_fetch_array($res)) {
    if(first) {
        // PRINT THE TOPIC NAME
        $first = false;
    }
    // PRINT THE TAG ROW
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.