简体   繁体   中英

Conditional join in Postgres

I have a Postgres table log_actions with fields:

id - id of the action
userId
action - BAN, ADD_PROCESS, etc...
action_id

action_id is the id from one of the following tables:
user_bans for action=BAN
user_processes for action=ADD_PROCESS

  1. My first question is it ok to have such kind of architecture. I mean action_id field which contains id to different tables.
  2. If it is then I would appreciate any help how to conditionally join log_actions, user_bans, user_processes. I read the documentation but didn't realize how to do it. Thanks in advance.

I'd advise against such a design, because it precludes the use of foreign keys for integrity control. (You may want to look into entity subclassing.) It also looks as if you have a normalisation issue in that action_id seems to functionally determine action without being a superkey.

This is a viable structure for handling "one-of" relationships. As Jon points out, you cannot declare foreign key relationships. That is a shame, so this is not a great solution.

Postgres offers table inheritance. This probably does exactly what you want. The "action" tables can all inherit actionid from an actions table. This can be used for the join. Each table can then have its own specific columns (and foreign key relationships).

Refer to the documentation for more information about inheritance.

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