简体   繁体   中英

Mysql: Multiple relations between one field of a table and two fields from another table

I try to explain it as simple as possible. Lets say I have 2 tables in my MySql/MariaDB database.

PEOPLE (id,name)

ID  NAME
0   John
1   Jack
2   Jane
3   Lily
4   Ruth
... ...

RELATIONSHIP (id1,id2,rel)

ID1  ID2  REL
0    1    father
1    0    son
3    0    boss
2    3    daughter
3    2    mother
...  ...  ...

The first table contains the names of some people and the second contains the relationship between people every line tells me the relationship between two people from table PEOPLE ). For example the first line of table RELATIONSHIP tells me that John (ID 0) is the father of Jack (ID 1) .

How can I write a query that gives me the following table?

ID1  NAME1  ID2  NAME2  REL
0    John   1    Jack   father
1    Jack   0    John   son
3    Lily   0    John   boss
2    Jane   3    Lily   daughter
3    Lily   2    Jane   mother
...  ...    ...  ...    ...

Is it possible with only one query? I can't figure out how to join both ID1 and ID2 to different lines of table PEOPLE .

This tables are just an example to explain what I need.

Thanks in advance!

You simply use two join s:

select r.*, p1.name as name1, p2.name as name2
from relationship r join
     people p1
     on r.id1 = p1.id join
     people p2
     on r.id2 = p2.id;

Simply use 2 joins.

SELECT 
  r1.ID as ID1, 
  r1.NAME as NAME1, 
  r2.ID as ID2, 
  r2.NAME as NAME2,
  relationship.REL as REL
FROM relationship 
  JOIN PEOPLE as r1 ON relationship.ID1 = r1.ID
  JOIN PEOPLE as r2 ON relationship.ID2 = r2.ID

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