Thursday, December 11, 2008

MySQL - help needed please!

Hi everyone,

I'm running into a brick wall when it comes to joining two tables together in mysql. Can anyone help?

Here's the situation: I have two tables. One table contains a list of news items from a bunch of different RSS feeds (feeditem table). The other table contains a list of all the feed titles and the category for each feed (feeds table). Both tables contain a field with the feed title.

I would like to construct a query that takes a category as input and then pulls the relevant news items. I've been trying various forms of join queries, but I don't seem to be getting anywhere. My latest attempt at a function is below.

Some of my questions:
Is it ok to have a query broken up on different lines for easier readability? Will it still run?

If the array is made successfully, am I correct in assuming that the variables will all have new names? What used to be "id" will now be "table_name.id"?

Should I be using something other than a left join?

I would appreciate any help!
- Sharon


function getSectionFeedItems($section) {

$myQuery = "SELECT snikfarjam_feeditem.id, snikfarjam_feeditem.feedid, snikfarjam_feeditem.feedurl, snikfarjam_feeditem.hash, snikfarjam_feeditem.guid, snikfarjam_feeditem.linkurl snikfarjam_feeditem.enclosureurl, snikfarjam_feeditem.title, snikfarjam_feeditem.content, snikfarjam_feeditem.pubdate, snikfarjam_feeditem.created, snikfarjam_feeds.category
FROM snikfarjam_feeds
LEFT JOIN snikfarjam_feeditem
ON snikfarjam_feeditem.feedid = snikfarjam_feeds.feed_name
WHERE snikfarjam_feeds.category={$section}
ORDER BY pubdate desc";

//run the query
$result = mysql_query($myQuery);


if ($result) {
//create an array that will store the results
$arrSectionItems = array();

//loop through the results returned from the database here
while($row = mysql_fetch_array($result)) {
$arrSectionItems[] = $row;
}
} //end if results

return $arrSectionItems;
}

1 comment:

JanetP said...

Hi Sharon,
If the common field between the two tables is feed_title, then you will have to join on feed_title.
E.g.,

SELECT I.id, I.feedid, I.feedurl, I.hash, I.guid, I.linkurl, I.enclosureurl, I.title, I.content, I.pubdate, I.created, I.category FROM snikfarjam_feeds F, snikfarjam_feeditem I WHERE F.feed_title = I.feed_title AND F.category = {$section} ORDER BY pubdate desc

Having line breaks within your query will cause problems. If you want to do that you could use concatenation to form the string, e.g.

my_query = "select id, ".
"title, ".

etc...

Hope this helps.

Janet