1

我有一个包含交易记录的数据库。每条记录都属于一个交易链,这些交易有一个它们共享的 TCID(交易链 ID)。每个事务都包含一个发送者和一个接收者。我需要做的是检查链中的最终接收用户是否与另一个链中的第一个发送者相同。

目前,我的 MySQL 查询返回最终接收者在另一个链的任何事务中的记录,而不仅仅是第一个。我需要将其严格限制为最终接收者和第一个发送者。

我尝试使用 group by、order by 和 limit 1,但在查询找到一些记录后应用这些。这是我到目前为止尝试过的查询:

SELECT TCID FROM transactions WHERE senderUID = '$receiverUID' GROUP BY TCID LIMIT 1

任何人都知道我可以只搜索组中第一个(最低 TID)记录(TCID)的 senderUID 的方法吗?

谢谢你的帮助!

4

1 回答 1

1

这应该有望使您朝着正确的方向前进-

//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)

senderUID/receiverUID 的 TCID 组为 1

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

senderUID/receiverUID 的 TCID 组为 1,仅限制第一行 senderUID

同样的想法,如果我设置 $receiverUID = 2 (3,11)/(6,10)

senderUID/receiverUID 的 TCID 组为 2

LIMIT 1(3)/(6,10)

senderUID/receiverUID 的 TCID 组为 2,仅限制第一行 senderUID

于 2012-09-18T06:39:51.150 回答