Add data to many-to-many relation with one SQL command

删除回忆录丶 提交于 2021-01-01 08:12:18

问题


I have a basic understanding of SQL databases and I might overlooked something, but I cannot figure out the following problem: there is a many-to-many relationship (for example: users - user_roles - roles). Is it possible to add (new) role to a (new) user with one SQL command (atomic operation)? Currently I use Sqlite.

I am aware of the SELECT last_insert_rowid(); command and with this and several SQL commands I can achieve what I want. But I want to incorporate it into one command (so the server, in this case Sqlite, can optimize the query, etc.). I have no idea, how it is done in real life (one command vs. several one in one transaction), that´s the root cause of this question.

So far this is what I was able to do:

pragma foreign_keys = on;

CREATE TABLE users (
  user_id integer primary key autoincrement,
  user_name text not null unique
);

CREATE TABLE roles (
  role_id integer primary key autoincrement,
  role_name text not null unique
);

CREATE TABLE user_roles (
  user_id integer not null,
  role_id integer not null,
  foreign key (user_id) references users(user_id),
  foreign key (role_id) references roles(role_id),
  primary key (user_id, role_id)
);

insert into users (user_name) values ('Joe');
insert into roles (role_name) values ('admin');

insert into user_roles (user_id, role_id) values (
  (select user_id from users where user_name = 'Joe'),
  (select role_id from roles where role_name = 'admin')
);

If both user and role exists (Joe and admin), then it works fine. But I cannot figure out, how to achieve "add-if-missing-then-return-id" behavior if Joe or admin is mission from database.

Example (both user and role are missing):

insert into user_roles (user_id, role_id) values (
  (select user_id from users where user_name = 'Bill'),
  (select role_id from roles where role_name = 'user')
);

Result:

Execution finished with errors.
Result: NOT NULL constraint failed: user_roles.user_id

回答1:


You could create view from user_roles table:

CREATE VIEW user_roles_view AS
  SELECT
    U.user_name, R.role_name
  FROM user_roles AS UR
    INNER JOIN users AS U ON u.user_id = UR.user_id
    INNER JOIN roles AS R ON r.role_id = UR.role_id;

Views in SQLite are read-only unless you create an INSTEAD OF trigger on it. This way you can specify a command or sequence of commands that are executed when the view is modified using INSERT, UPDATE or DELETE statement. For INSERT it could go like this:

CREATE TRIGGER user_roles_view_insert INSTEAD OF INSERT ON user_roles_view
BEGIN
  INSERT OR IGNORE INTO users (user_name) VALUES (NEW.user_name);
  INSERT OR IGNORE INTO roles (role_name) VALUES (NEW.role_name);
  INSERT OR IGNORE INTO user_roles (user_id, role_id) VALUES (
    (SELECT user_id FROM users WHERE user_name = NEW.user_name),
    (SELECT role_id FROM roles WHERE role_name = NEW.role_name)
  );
END;

Note the usage of INSERT OR IGNORE to prevent inserting duplicate values into all of the three tables. Here's how you would insert values via the view:

INSERT INTO user_roles_view VALUES ('Joe', 'admin');
-- The above statement creates:
--   a row (1, 'Joe') in table users,
--   a row (1, 'admin) in table roles,
--   a row (1, 1) in table user_roles.

INSERT INTO user_roles_view VALUES ('Joe', 'admin');
-- The above statement doesn't add any additional records, because all appropriate records
-- already exist.

INSERT INTO user_roles_view VALUES ('Joe', 'system');
-- The above statement creates:
--   a row (2, 'system') in table roles,
--   a row (1, 2) in table user_roles.

INSERT INTO user_roles_view VALUES ('Alice', 'admin'), ('Bob', 'system');
-- The above statement creates:
--   a row (2, 'Alice') in table users,
--   a row (3, 'Bob') in table users,
--   a row (2, 1) in table user_roles,
--   a row (3, 2) in table user_roles

All of the above statements produce the following output from user_roles_view (SELECT * FROM user_roles_view):

user_name role_name
Joe admin
Joe system
Alice admin
Bob system


来源:https://stackoverflow.com/questions/65343126/add-data-to-many-to-many-relation-with-one-sql-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!