1

我有一个消息列,我试图弄清楚我应该如何在“已发送”文件夹中显示消息。

我运行以下查询:

 SELECT
    `text`,
    `created`
 FROM
    `messages`
 WHERE
    `status` = 1
 ORDER BY `created` DESC
 LIMIT 1

我想引入一个条件,以便仅当最后一行status = 1也有时才返回结果user_from = $user(如果最后一行有user_to = $user,那么什么都不应该返回)。

我的查询应该是什么?

4

3 回答 3

2

你可以使用一个subquery

select `text`, `created` from T1
( SELECT
    `text`,
    `created`
 FROM
    `messages`
 WHERE
    `status` = 1
 ORDER BY `created` DESC
 LIMIT 1) T1
where `user_from` = $user and `user_to` != $user
于 2012-08-16T13:50:43.947 回答
0

Select the latest message with status=1 and then use it as a nested query and check your conditions to output this one row result or not:

   select `text`, `created`
    from
    (
        SELECT
            `text`,
            `created`,
             user_from,
             user_to
         FROM
            `messages`
         WHERE
            `status` = 1
         ORDER BY `created` DESC
         LIMIT 1
        ) t
        where (user_from = $user) 
              and (not (user_to = $user))
于 2012-08-16T13:54:16.377 回答
0

如果我正确理解您的问题,您是否要这样做:

SELECT
    `text`,
    `created`
 FROM
    `messages`
 WHERE
    `status` = 1
    AND `user_from` = $user 
    AND `user_to` != $user
 ORDER BY `created` DESC
 LIMIT 1

当然你需要$user用你的字符串替换,或者使用准备好的语句将变量插入到查询中。

于 2012-08-16T13:51:44.790 回答