2012-05-08 44 views
0

我有一些表格是這樣的:如何編寫返回給定用戶的最新消息的內部查詢?

USERS TABLE: 
| id | created | active | fname | lname | 

MESSAGES TABLE: 
| id | userId| active | date | content | 

我試圖返回一些用戶信息,以及最新添加的消息給定用戶。 下面是我rying達到的結果的結構:

| userId | userCreated | latestMessageDate| latestMessageContent | 

以下查詢返回用戶信息:

SELECT 
user.id, 
user.created 
FROM user 
WHERE user.active = 1 

...但我怎麼現在重視的日期最新消息,以及實際的最新消息?

我相信使用內部查詢就是這樣的一種方法,但是如何編寫這樣的查詢?

回答

2
SELECT u.fname, u.lname, m.id, m.userID, m.datem, m.content 
FROM USERS AS u 
LEFT JOIN (SELECT id, userID, date, content 
      FROM MESSAGES 
      WHERE active 
      ORDER BY date DESC) AS m 
ON u.id = m.userId 
WHERE u.active 
    # AND u.id = {$int_user_id} 
GROUP BY u.id 
1

也許是這樣的:

SELECT 
    Users.id AS userId, 
    Users.created AS userCreated, 
    LatestMessage.LatestMessageDate, 
    MESSAGES.content AS latestMessageContent 
FROM 
    Users 
    LEFT JOIN 
    (
     SELECT 
      MAX(date) AS LatestMessageDate, 
      MESSAGES.userId 
     FROM 
      MESSAGES 
     GROUP BY 
      MESSAGES.userId 
    ) AS LatestMessage 
    ON Users.id=LatestMessage.userId 
    LEFT JOIN MESSAGES 
     ON LatestMessage.LatestMessageDate=MESSAGES.date 
     AND LatestMessage.userId=MESSAGES.userId 
相關問題