我非常感谢任何尝试简化 MySQL 查询的帮助。查询的目的是从消息表 (users_messages) 中检索消息,该表具有以下列:message_id、from_id、to_id、message_content、date_sent。
from_id 和 to_id 需要加入一个包含以下列的用户表(用户):user_id,user_username。
另外我应该提到有一个被阻止的用户表(users_blocked),如果该表中的 user_id 功能,它会过滤掉任何消息。
所有这些都可以正常工作,并且消息以最新的优先顺序排序,这正是我想要的。我唯一的问题是它没有提取相应的“message_content”。即它正在拉最近的日期,但不是最近的消息。
也许我需要一种不同的方法(例如子查询),但我无法理解它。
这是查询:
select m.message_content,
if(from_id < to_id, concat(from_id,to_id), concat(to_id,from_id)) as ft,
if (from_id = $my_id, to_id, from_id) as other_id,
max(date_sent) as most_recent
from users_messages m
left join users_blocked ub1 on (from_id = ub1.blocked_id and ub1.user_id = $my_id)
left join users_blocked ub2 on (to_id = ub2.blocked_id and ub2.user_id = $my_id)
where
(from_id = $my_id or to_id = $my_id)
and ub1.blocked_id is null
and ub2.blocked_id is null
group by
ft
order by
most_recent desc
对不起,这里是表结构:
用户
用户 ID 用户用户名 1西蒙 2 琥珀色 3 汤姆
users_messages
message_id from_id to_id date_sent message_content 1 1 2 2012-07-04 11:52:12 你好 2 1 2 2012-07-04 12:32:24 另一个消息 3 1 2 2012-07-04 14:00:00 再次你好
users_blocked
user_id 被阻止的_id 1 3