仅从组中的第一个记录中选择值

时间:2012-09-16 18:13:50

标签: php mysql

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

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

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

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

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

感谢您的帮助!

1 个答案:

答案 0 :(得分: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

如果你想只获得1行,其中senderUID是TCID组中的第一个(1)/(4,7,8),你可以添加LIMIT 1

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