简体   繁体   中英

Join only one row in each table and vice versa

There are a lot of similar questions, which do not quite seem to cover what I want.

I have 2 tables:

THREEGRAM  POSITION
^^B        1
^BA        2
BAK        3
AKA        4
KAC        5
ACE        6
CEV        7
EVA        8
VA$        9
A$$        10

and

THREEGRAM  POSITION
^^S        1
^SO        2
SOR        3
ORK        4
RKO        5
KOC        6
OCE        7
CEV        8
EVI        9
VIC        10
ICE        11
CEV        12
EVA        13
VA$        14
A$$        15

I can join these table to have the following result:

select * from t1
join t2 on t1.threegram = t2.threegram

THREEGRAM  POSITION THREEGRAM  POSITION
CEV        7        CEV        8
CEV        7        CEV        12
EVA        8        EVA        13
VA$        9        VA$        14
A$$        10       A$$        15

This is not the result I am looking for; I only want POSITION (t1 and t2) to be listed once and it should be one where ABS(t1.POSITION - t2.POSITION) is minimal.

I figured out how to do this one way by using GROUP BY:

select t1.threegram, t1.POSITION, min(abs(t1.position-t2.position)) as MinPosition 
from t1     
join t2 on t1.threegram = t2.threegram
group by t1.threegram, t1.POSITION
order by t1.POSITION

THREEGRAM  POSITION MinPosition
CEV        7        1
EVA        8        5
VA$        9        5
A$$        10       5

The problem is that I want a solution that works both ways, ie when I switch t1 and t2 in the above query, the result should be similar and return 4 rows.

You can't, really. The first table is unique in that there aren't any redundancies, while the second table has multiple entries for the same 'threegram'. The first idea that comes to mind is to perform a self join on a UNION of the 2 tables, which will do what you need albeit inefficiently.

It may be helpful to know why you need to be able to do this both ways, if this way works perfectly fine.

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