简体   繁体   中英

How to make this relation in PostgreSQL?

多对多整体参与关系(双向)

Hello.

As shown in the ER model, I want to create a relation between "Busses" and "Chauffeurs", where every entity in "Chauffeurs" must have at least one relation in "Certified", and every entity in "Busses" must have at least one relation in "Certified".

Though it was pretty easy to design the ER model, I can't seem to find a way of making this relation in PostgreSQL. Anybody got some ideas ?

Thanks

The solution should be database agnostic. If I understand you correctly, you probably want your certified table to look like:

CERTIFIED
id
bus_id
chauffer_id
...
...

The only solution I've been able to find is the notion of a single mandatory field in the parent table to represent the "at least one" and then storing the 2 or more relationships in the intersection table.

chauffeurs

chauffeur_id
chauffer_name
certified_bus_id (not null)

certified

chauffer_id
bus_id

busses

bus_id
bus_name
certified_chauffer_id (not null)

To get a list of all busses where a chauffer is certified becomes

select c.chauffer_name, b.bus_name
from chauffeurs c
inner join busses b on (b.bus_id = c.certified_bus_id)
UNION
select c.chauffer_name, b.bus_name
from chauffeurs c
inner join certified ct on (c.chauffeur_id = ct.chauffer_id)
inner join busses b on (ct.bus_id = b.bus_id)

The UNION (vs UNION ALL) takes care of deduplication with the values in certified .

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