Jump to content

Query help?


Mr Chris

Recommended Posts

Hi All,

 

I have a query in php which works great:

 

$query = mysql_fetch_array(mysql_query("SELECT * FROM stories WHERE unix_timestamp(published) <= unix_timestamp(NOW()) order by story_id desc"));

 

 

However I want to incorporate another query in it, but I’m not sure how

 

$query = mysql_fetch_array(mysql_query("SELECT * FROM stories, (SELECT count(*) FROM comments WHERE story_id = stories.story_id)  WHERE unix_timestamp(published) <= unix_timestamp(NOW()) order by story_id desc"));

 

Can someone help?

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/107431-query-help/
Share on other sites

In order to do that, you will have to use a Join statement.  You can either do Left Join or an Inner Join.  I would suggest reading up on those so you can figure out which one you need, but it is real easy to switch between the 2 by just changing INNER to LEFT...so your query would look like

 

SELECT * FROM stories, (SELECT count(*) FROM comments WHERE story_id = stories.story_id)  WHERE unix_timestamp(published) <= unix_timestamp(NOW()) order by story_id desc"

 

$query = "
   SELECT
      s.*,
      count(c.*) as total
   FROM
      stories as s
   INNER JOIN
      comments as c
   ON
     c.story_id = s.story_id
   WHERE
      unix_timestamp(s.published) <= unix_timestamp(NOW()) 
   ORDER BY
      s.story_id DESC
"

 

 

Link to comment
https://forums.phpfreaks.com/topic/107431-query-help/#findComment-550686
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.