这应该有望使您朝着正确的方向前进-
//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)
