简体   繁体   中英

Query for many-to-many relationship

I've got a database designed like:

t_relationships

  • id (unique)
  • relationship_uuid
  • actor_uuid

t_actor

  • id (unique)
  • actor_uuid
  • name_or_whatever_doesnt_matter

The relationship table has many actors with one relationship_uuid .

I'm having problems with efficient query that will give me all the actors in a relationship with a given actor.

For instance, if actor table have entries [1,1,cat], [2,2,dog], [3,3,tree], [4,4,box]

and relationship has [1,1,1], [2,1,2], [3,1,3], [4,2,1] [5,2,4], [6,3,2], [7,3,4] .

What's the best way to find out who is in a relationship with a cat?

You don't need the id columns. You can just drop them. A join is what you are looking for

select ar.name
from t_actor a
join t_relationships r on r.actor_uuid = a.actor_uuid
join t_actor ar on ar.actor_uuid = r.relationship_uuid
where a.name = 'cat'

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