沿10个接触我有一个跟进复杂MySQL的问题,我最近问:Show the ten first contacts that I have recieved messageSQL:第一,我收到消息来自或发送到他们的最新发送的消息和时间
现在我知道,这是失去了一些东西,我的最后一个问题是:
我想创建SQL语句 表明我 已经从 他们的最新发送的消息和时间收到消息十个第一次接触。 表列为messageId, 消息,来自ProfileId,属于ProfileId, timeStamp和表被称为 消息。数据库是Mysql,并且是Java语言。但我希望这个 发生在一个单一的SQL语句。
什么是缺少的是我想说明我还发来的消息,但它应该与我已经发送到我已经从用户收到邮件进行分组:
我有 收到消息或发送到 与他们最新发送的消息和 时间的十个第一联系人。
有点难理解?好。这样想。上面引用的第一个sql语句仅显示我从中获得的消息。但是如果我发送消息呢?该消息将永远不会显示。
这是我的代码,但我没能赢得成功(看看那里我标记注释):
"SELECT M2.messageProfileId, profiles.profileMiniature, profiles.firstName, profiles.lastName, profiles.timeFormat, lastMessages.message, lastMessages.timeStamp " +
"FROM (" +
" SELECT IF(M1.fromProfileId = ?, M1.toProfileId, M1.fromProfileId) AS messageProfileId, " +
" max(M1.timeStamp) AS lastMessageTime " +
" FROM messages AS M1 " +
" WHERE M1.toProfileId = ? " +
" OR M1.fromProfileId = ? " +
" GROUP BY IF(M1.fromProfileId = ?, M1.toProfileId, M1.fromProfileId) " +
" ORDER BY max(M1.timeStamp) DESC " +
" LIMIT 10 " +
" ) AS M2 " +
"INNER JOIN messages AS lastMessages " +
"ON (" +
" lastMessages.timeStamp = M2.lastMessageTime " +
"AND lastMessages.fromProfileId = M2.messageProfileId" +//This to be like the if statements above, but how?
" )" +
"INNER JOIN profiles " +
"ON M2.messageProfileId = profiles.profileId ";
UPDATE:
在上面的代码中所有的问号将被替换AA相同的id,例如27
UPDATE:
你只需要现在解决一行。看看上面的注释行。我不知道如何在where语句中声明if语句?
是'messageProfileId'一样'messageId'? – 2011-03-04 23:30:51
否messageProfileId是与该消息相关的profileId。和profileId是一样的userid,但在这种情况下,我称之为profileId。通过相关我的意思是来自ProfileId或toProfileId,取决于我是否收到消息或者如果我发送了消息 – einstein 2011-03-04 23:35:32
messageId是消息的主键就像只是索引 – einstein 2011-03-04 23:40:07