简体   繁体   中英

Select value from only the first record in a group

I have a database that contains transaction records. Each record belongs to a chain of transactions, and these have an TCID (Transaction Chain ID) that they share. Each transactions contains a sender and a receiver. What I need to do is check to see if the final receiving user in a chain is ever the same as the first sender in another chain.

Currently, my MySQL query returns records where the final receiver is in any transaction of another chain, not just the first. I need to limit this strictly to final receiver and first sender.

I tried using group by, order by, and limit 1, but these are applied after the query finds some records. Here's the query I had tried so far:

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

Anyone know of a way that I can search only the senderUID of the first (lowest TID) record in a group (TCID)?

Thanks for your help!

This should hopefully get you in the right direction -

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

So as simple example I have the following table-

表数据

And so if I set $receiverUID = 1, I get 2 rows where senderUID was the first in a TCID group (1,9), and 3 rows where that senderUID was the receiverUID in a TCID group (4,7,8)

senderUID / receiverUID的TCID组为1

And you could add a LIMIT 1 if you wanted to only get 1 row where the senderUID was the first in a TCID group (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

Same idea if I set $receiverUID = 2 (3,11)/(6,10)

senderUID / receiverUID的TCID组为2

and with LIMIT 1 (3)/(6,10)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM