tags:

views:

45

answers:

2

I am a little confused on the logic of how to write this SQL statement. When a user clicks on a tag, say HTML, it would display all the posts with HTML as its tag. (a post can have multiple tags)

I have three tables:

  1. Posting-->posting_id, title, detail, etc
  2. tags-->tagID, tagname
  3. postingtag-->posting_id, tagID

I want to display all the title of the post and the date added.

    global $dbc;
    $tagID=$_GET['tagID']; //the GET is set by URL

    //part I need help with. I need another WHERE statment to get to the posting table
    $query = "SELECT p.title,p.date_added, t.tagname FROM posting as p, 
    postingtag as pt, tags as t WHERE t.tagID=$tagID";

   $data = mysqli_query($dbc, $query);

  echo '<table>';
  echo '<tr><td><b>Title</b></td><td><b>Date Posted</b></td></tr>';
  while ($row = mysqli_fetch_array($data)) {         
     echo '<tr><td>'.$row['title'].'</td>';
     echo '<td>'.$row['date_added'].'</td></tr>';
     }
  echo '</table>';
}

I am fairly new to mySQL so still trying to figure out the logic of it all :)

+4  A: 

This is more clearly written using ANSI syntax:

select p.title, p.date_added, t.tagname 
from posting p
inner join postingtag pt on p.postingID = pt.postingID
inner join tags t on pt.tagID = t.tagID
where t.tagID=$tagID
RedFilter
Wow, you made it look so simple. Thanks! May I ask how you came up with this logic?
ggfan
Are you basically saying to first match the tagID of the GET with the tagID of the tags table. Then you make a connection between the posting and postingtag table by saying p.postingID=pt.postingID.is that correct?
ggfan
@ggfan it's quite simple: [postings]--->[postingtag]<---[tags], so postingtag will join the line in postingtag with it's id matching, then postingtag will join the line in tag that match the tag id. You should read tutorials on Google about the join keyword in SQL. :)
Erick
When you have joined all three tables, how does the WHERE statement know to get the correct posting_id from the posting table? because aren't you just making sure the tagID matches?
ggfan
A: 

OrbMan's solution is great! I thought it might help you understand better to see how to do the same query using your original cross product between tables. If you want to keep the original syntax, you would have to add some additional where conditions:

SELECT p.title, p.date_added, t.tagname
FROM
posting as p, 
postingtag as pt,
tags as t
WHERE
    p.postingID = pt.postingID AND pt.tagID = t.tagID AND t.tagID = $tagID
David Smith
You still need table `tags` in order to get the tagname...
RedFilter
Thanks, I forgot that part. I removed that statement from my answer.
David Smith