S
S
Senture2019-03-28 19:17:17
SQL
Senture, 2019-03-28 19:17:17

INSERT INTO insert different values ​​in one query, how?

There are 3 tables:
users - has 2 fields username and id;
users_clans - has 3 fields user_id, clan_name and rep;
clans - has 1 name field.
I need to add the following data to the users_clans table:
user_id = 10
clan_name = if "Clan1", then the rep field = 1,
and if clan_name != "Clan1" (there may be hundreds of other names), then the rep field = -1.
I was able to compose a query like this:

INSERT INTO users_clans (user_id, clan_name, rep) 
VALUES ((SELECT id FROM users WHERE username = 'Maaax'), 'Клан1', 1), 
((SELECT id FROM users WHERE username = 'Maaax'), 
(SELECT name FROM clans WHERE name != 'Клан1'), -1)

But it doesn't work because: "The subquery returns more than one record", it's because of this subquery: "(SELECT name FROM clans WHERE name != 'Clan1')" and it's logical, but I don't understand how to write the correct query .

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vapaamies, 2019-03-31
@Senture

insert into users_clans
  (user_id, clan_name, rep) 
select
  u.id, c.name, case when c.name = 'Клан1' then 1 else -1 end
from
  users u,
  clans c
where
  1 = 1 -- условия соединения нет, подразумеваем декартово произведение

K
Konstantin Tsvetkov, 2019-03-28
@tsklab

Subquery returns more than one record
Simply without .INSERT ... SELECTVALUES
it is necessary to add the following data to the users_clans table
You have other conditions in requests INSERT INTO.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question