2012-08-16 101 views
1

我有一列消息,我想弄清楚应该如何在“已发送”文件夹中显示消息。只有在满足where条件的情况下才能选择最后一行

我运行下面的查询:

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

我想介绍一个条件,使返回的结果,只有当最后一行status = 1也有user_from = $user(如果最后一排有user_to = $user,然后什么应该是回)。

我的查询应该是什么?

回答

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 
0

如果我正确理解你的问题,你要做到这一点:

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

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

+0

这将返回被'发来的最新消息$ user' ..我需要它,只有当发送的最后一条消息是'$ user'时才返回结果(如果最后一条消息不是由$ user发送的,则不应返回任何内容) – kapeels 2012-08-16 13:59:16

0

选择与状态= 1的最新消息,然后把它作为一个嵌套查询,并检查你的条件,输出这一行的结果或不:

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)) 
相关问题