开发者

How do I write this SQL statement to get the ad and posting? (PHP/MySQL)

开发者 https://www.devze.com 2022-12-26 15:11 出处:网络
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 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>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
0

精彩评论

暂无评论...
验证码 换一张
取 消