0

我需要获取未答复的最新消息,请考虑下表:

用户元

userid   metakey    metavalue
-----|------------|-------
 12  | "thekey"   | true
 41  | "thekey"   | true

信息

sender  reciepent   content       date
-----|------------|--------------|-----------------
 12  | 0          | "lorem ipsum"|2013-08-12 21:20:31
 0   |12          | "lorem ipsum"|2013-08-12 20:20:31
 41  |50          | "lorem ipsum"|2013-08-12 18:20:31
 50  |41          | "lorem ipsum"|2013-08-12 19:20:31

现在我想获取对话中其他人没有回答并且由具有usermeta "thekey" = true的用户编写的消息

我尝试了几种想法,但都没有奏效。我很想得到一些帮助。抱歉,如果我做错了什么,这是我在这里的第一篇文章。

4

3 回答 3

0

如果您有任何唯一/主要的 id 来存储您的聊天而不是检索最后一条消息,您可以使用名为 mysql 的函数:mysql_insert_id(); 它将为您提供最后插入的消息的 id,您可以通过 id 检索您的消息。

谢谢。

于 2013-10-14T12:03:53.747 回答
0

由于您使用的是 Wordpress,我假设您也在使用 MySQL。我手头没有任何 MySQL 数据库,但我使用 T-SQL 将这个查询放在一起,您可以将其转换为 MySQL。

这个想法是使用一个临时表来存储每个用户在每个对话中的最后一条消息,然后查找哪些未答复的消息并检查用户元数据。我希望这可以帮助你。

create table #tmpLastMsg (
    sender int,
    reciepent int,
    msgdate datetime
)

-- get the last message from each user in every conversation
insert into #tmpLastMsg
select sender, reciepent, MAX(msgdate)
from Message
group by sender, reciepent

select m.*
from Message as m
inner join (
    select msg.*
    from #tmpLastMsg as msg
    left join #tmpLastMsg as rep -- this join tries to find if there was a reply
        on msg.sender = rep.reciepent
        and msg.reciepent = rep.sender
        and rep.msgdate > msg.msgdate
    inner join usermeta as um on msg.sender = um.userid
    where rep.sender is null -- we want unreplied messages
        and um.metakey = 'thekey'
        and um.metavalue = 'true'
) as t on m.sender = t.sender
    and m.reciepent = t.reciepent
    and m.msgdate = t.msgdate
于 2013-10-15T21:12:10.327 回答
0

试试这个:

select t.sender,t.reciepent,m2.content 
from 
(
select
sender,reciepent,
(select count(*) from messages m where m.sender = sender and m.reciepent = reciepent) sent,
(select count(*) from messages m where m.sender = reciepent and m.reciepent = sender) rec
from messages m
) t 
inner join messages m2 on t.sender = m2.sender and t.reciepent = m2.reciepent
inner join usermeta u on u.userid = t.sender
where t.sent>t.rec and m2.date = (select max(m3.date) from messages m3 where m3.sender = m2.sender and m3.reciepent = m2.reciepent) and u.metakey='thekey'
于 2013-10-14T11:33:16.930 回答