Jump to content

SQL query help


BigP

Recommended Posts

Hello!

 

I\'ve been trying to optimize a few of my queries in a program I wrote but I\'m getting a little lost. Here is a half written SQL query:

 


  $sql = \'SELECT e.id, e.posterid, e.titletext, m.username\'

       . \' FROM phpnews_news e, phpnews_posters m\'

       . \' WHERE e.posterid = m.id\'

       . \' ORDER BY e.id DESC\';

       

       $SQL_query = mysql_query($sql);

       

       while ($posts = mysql_fetch_array($SQL_query))

       {

         // Do stuff

       }

My tables are like so:

 

phpnews_news table holds all the news.

phpnews_posters table holds people allowed post news.

 

The name of the person who posts the news is in the phpnews_posters table. A foreign key, \"posterid\" is used to link them to an article. There\'s also a field called \"postername\" that stores the postersname in the phpnews_news table in case that particular news poster is deleted.

 

So, as you can see I am able to get the posters name from the phpnews_posters table, but I don\'t know how to use the \"postername\" field from phpnews_news if there is no matching ID in the posters table.

 

So basically if this isn\'t true:


. \' WHERE e.posterid = m.id\'

 

Any help is greatly appreciated! :) You\'d be helping me make an Open Sorce project better by helping me here! :)

 

Thanks!

Link to comment
Share on other sites

  • 2 weeks later...

You need to use an outer join : Here is an example

 

SELECT e.id, e.posterid, e.titletext, m.username

FROM phpnews_news e

LEFT JOIN phpnews_posters m ON e.posterid = m.id

ORDER BY e.id DESC

 

This will pull all of the data from phpnews_news and only the records in phpnews_posters that match. If you wanted to reverse this (pull all from posters and only those in news that match) you could change it to a RIGHT JOIN

 

http://www.mysql.com/doc/en/JOIN.html

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.