我跟进了我最近提出的复杂的mysql问题:Show the ten first contacts that I have recieved message
现在我知道它遗漏了一些东西,我的最后一个问题是:
我想创建那个Sql语句 显示我的十个第一次接触 收到了来自的消息 他们最新发送的消息和时间。 表列是messageId, 消息,fromProfileId,toProfileId, 调用timeStamp和table 消息。数据库是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 ";
更新
上述代码中的所有问号都将替换为相同的ID,例如27.
更新
你现在必须解决一行问题。看看上面的注释行。我不知道如何在where子句中创建if语句?
答案 0 :(得分:0)
好的,我自己想出来了
"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 " +
"OR lastMessages.toProfileId = M2.messageProfileId " +
" )" +
" )" +
"INNER JOIN profiles " +
"ON M2.messageProfileId = profiles.profileId ";