Select 根据 MySql 中的给定用户,两列中的唯一行

Select Uniq rows from two columns according to given user in MySql

我正在创建一个聊天系统,我的数据库看起来像

from  to  msg  date
----  -- ----  -----------------
a     b   hi    12-3-15 12:04:21
b     a   hi    12-3-15 12:12:21
c     b   hi    12-3-15 12:14:21
d     b   hi    12-3-15 12:14:21
a     b   msg1  12-3-15 12:12:21
a     b   msg2  12-3-15 12:50:23
a     b   msg3  12-3-15 13:44:21
b     a   msg1  12-3-15 15:12:21
b     e   hi    12-3-15  15:32:21
b     c   hi    12-3-15 16:12:21

我正在尝试查询 returns 使用 'b' 发送的最后一条消息或使用 'b' 接收的最后一条消息并输出

Actor b
----
c
e
a
d

我写了一个查询

(SELECT `to`
      , `from` 
 FROM databaseTable 
 WHERE from = 'b' 
 ORDER BY date desc) 

UNION 

(SELECT `to`
      , `from` 
 FROM databaseTable 
 WHERE to = 'b'
 ORDER BY date desc )

但它没有返回我想要的

这应该是 return b 发送或接收的最后一条消息。但我可能从你的问题中遗漏了一些东西,因为这与你的预期输出不符。

 (SELECT `to`
          , `from` 
     FROM databaseTable 
     WHERE from = 'b' OR to= 'b'
     ORDER BY date desc) 
  LIMIT 1;

尝试以下操作:

select distinct `to` as ActorB
from
(
    select * from
    (
        SELECT `to`,`date` 
        FROM databaseTable 
        WHERE from = 'b'
        UNION 
        SELECT  `from` , `date`
        FROM databaseTable 
        WHERE to = 'b'
    ) temp
    ORDER BY date desc
) temp

以上查询应该有效。