2010-02-02 67 views
2

我想做以下,但在一個查詢:MYSQL像一個連接,但只需要最新的一行?

$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 />"; 
} 

有一個用戶表和意見表,我想顯示用戶的列表,並在他們旁邊的最後意見的日期?

這是可能在一個單一的查詢?

回答

3

你可以這樣做使用下面的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'; 

或使用:

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; 
+0

謝謝頂一個工作完美! – Sam 2010-02-02 00:38:19

+0

@Sam:請考慮在這種情況下接受答案。另外,請注意,性能方面,這些查詢確實不能很好地擴展。 – 2010-02-02 00:49:39

相關問題