选择具有特定值的行后面的行

时间:2011-02-26 09:29:39

标签: mysql sql phpmyadmin logic

嘿,再次,我仍然得到一堆查询和东西所以请原谅所有频繁的SQL问题8)

无论如何我试图在某个值之后选择行。 不懂?好的,这就是它的实际外观。

表:消息

+------------+-----------+---------+-------+---------------------------------------+----------------+------------------+
| message_id | thread_id | user_id | to_id | body                                  | message_status | uid_sent_deleted |
+------------+-----------+---------+-------+---------------------------------------+----------------+------------------+
|          1 |         1 |       1 |     7 | How are you bro?                      | read           |                1 |
|          2 |         1 |       7 |     1 | IM good what about you kenny?         | read           |                0 |
|          3 |         1 |       1 |     7 | Same just chilling how is your sister | read           |                1 |
|          4 |         1 |       7 |     1 | Shes coool u know just doin great     | read           |                0 |
|          7 |         1 |       1 |     7 | Thats nice                            | read           |                1 |
|          8 |         1 |       7 |     1 | Yupp                                  | read           |                0 |
|          9 |         1 |       1 |     7 | hhahaha                               | read           |                1 |
|         10 |         1 |       7 |     1 | anyways....                           | unread         |                0 |
+------------+-----------+---------+-------+---------------------------------------+----------------+------------------+

如果消息ID为9,则uid_sent_deleted列中的值为“1”。 我试图在uid_sent_deleted列中选择值为“1”的最后一行之后的行。

这是我目前正在使用的sql。谢谢你的帮助!!

SELECT message_id, thread_id, messages.user_id, to_id, body, message_status, uid_sent_deleted
FROM messages
INNER JOIN messages_thread ON messages_thread.id = messages.thread_id
WHERE thread_id =1
GROUP BY messages.message_id
ORDER BY message_id ASC 

3 个答案:

答案 0 :(得分:3)

... WHERE thread_id = 1 AND id > 
     (SELECT MAX(id) FROM messages WHERE uid_sent_deleted = 1)

答案 1 :(得分:1)

SELECT message_id, thread_id, messages.user_id, to_id, body, message_status, uid_sent_deleted
FROM
    (SELECT thread_id t_id, MAX(message_id) m_id
     FROM messages
     WHERE thread_id =1 and uid_sent_deleted = 1
     GROUP BY thread_id) n
inner join messages on messages.message_id > n.m_id and messages.thread_id = n.t_id
INNER JOIN messages_thread ON messages_thread.id = messages.thread_id
ORDER BY message_id ASC
LIMIT 1

答案 2 :(得分:0)

子查询可能有效,你选择MAX(message_id)WHERE uid_sent_deleted = 1,然后你加入......语法上有点朦胧。