这样应该可以让你在正确的方向 -
//Gets rows where senderUID is the first (lowest TID) record in group
SELECT a.*
FROM test a
WHERE a.senderUID = '$receiverUID'
AND NOT EXISTS (select * from test where TCID = a.TCID and id < a.id and senderUID != '$receiverUID')
GROUP BY TCID
UNION
//Gets rows where senderUID is the same as the last receiverUID of TCID
SELECT b.*
FROM test b
WHERE b.receiverUID = '$receiverUID'
AND NOT EXISTS (select * from test where TCID = b.TCID and id > b.id and receiverUID != '$receiverUID')
GROUP BY TCID
因此,作为简单的例子,我有以下表 -
所以,如果我设置$ receiverUID = 1,我得到2行,其中senderUID是TCID组中的第一个(1,9),以及3行,其中senderUID是TCID组中的receiverUID(4,7,8)
而且你可以添加一个LIMIT 1
如果你想只得到1列,其中senderUID是TCID组中的第(1)/(4,7,8)
SELECT a.*
FROM test a
WHERE a.senderUID = '$receiverUID'
AND NOT EXISTS (select * from test where TCID = a.TCID and id < a.id and senderUID != '$receiverUID')
GROUP BY TCID LIMIT 1
同样的想法,如果我设置$ receiverUID = 2(3,11)/(6,10)
和与LIMIT 1
(3)/(6,10)