How do I write this SQL statement to get the ad and posting? (PHP/MySQL)
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:
- Posting-->posting_id, title, detail, etc
- tags-->tagID, tagname
- 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>T开发者_StackOverflowitle</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 :)
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
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
精彩评论