0

我有一些这样的表:

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

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

我正在尝试返回一些用户信息,以及给定用户最近添加的消息。以下是我想要实现的结果的结构:

| userId | userCreated | latestMessageDate| latestMessageContent |

以下查询返回用户信息:

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

...但是我现在如何附上最新消息的日期以及实际的最新消息?

我相信使用内部查询是一种这样的方法,但是您如何编写这样的查询呢?

4

2 回答 2

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
于 2012-05-08T11:27:05.717 回答
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
于 2012-05-08T11:39:56.580 回答