views:

56

answers:

1

I want to do the following but in one query:

$query = mysql_query("SELECT name FROM tbl_users WHERE category = '1'");
while($row = mysql_fetch_assoc($query))
{
$query2 = mysql_query("SELECT datecreated 
                       FROM tbl_comments 
                       ORDER BY datecreated DESC LIMIT 1");
$row2 = mysql_fetch_assoc($query2);
echo $row['name'] . " > " . $row2['datecreated'] ."<br />";
}

There is a user table and a comments table, I want to display a list of users and the date of the last comment next to them?

Is this possible in a single query?

+3  A: 

You can do so using the following SQL:

SELECT name,
       (
        SELECT datecreated
          FROM tbl_comments
          WHERE tbl_users.user_id = tbl_comments.user_id
          ORDER BY datecreated LIMIT 1
       )
FROM tbl_users
WHERE category = '1';

OR using:

SELECT tbl_users.name, MAX(datecreated) AS latestcomment
  FROM tbl_users LEFT JOIN tbl_comments ON (tbl_users.user_id = tbl_comments.user_id)
  GROUP BY tbl_users.name;
Andrew Moore
thank you the top one worked perfect!
Sam
@Sam: Please consider accepting the answer in that case. Also, note that performance wise, those queries really do not scale well.
Andrew Moore