這樣應該可以讓你在正確的方向 -
//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)
