2012-09-16 76 views
1

我有一个包含事务记录的数据库。每条记录属于一个交易链,并且这些记录具有它们共享的T​​CID(交易链ID)。每笔交易包含一个发件人和一个收件人。我需要做的是检查链中的最终接收用户是否与另一个链中的第一个发送者相同。仅从组中的第一条记录中选择值

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

我试着使用group by,order by和limit 1,但是这些都是在查询发现一些记录之后应用的。这里的查询我到目前为止已经试过:

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

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

感谢您的帮助!

回答

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 

因此,作为简单的例子,我有以下表 -

table data

所以,如果我设置$ receiverUID = 1,我得到2行,其中senderUID是TCID组中的第一个(1,9),以及3行,其中senderUID是TCID组中的receiverUID(4,7,8)

TCID group for senderUID/receiverUID as 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 

TCID group for senderUID/receiverUID as 1, limit only first row senderUID

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

TCID group for senderUID/receiverUID as 2

和与LIMIT 1(3)/(6,10)

TCID group for senderUID/receiverUID as 2, limit only first row senderUID

相关问题