简体   繁体   中英

How do I select distinct and then perform a multi-insert for each of the distinct results?

I want to select all of the distinct orgId s in a table and then run this insert query for each of the distinct results into the same table?:

INSERT into "ffOrgs" (id, "ffId", "orgId", value, enabled, "createdAt", "updatedAt")
values (uuid_generate_v4(), 1111 , ABC, null, now(), now(), true),
( uuid_generate_v4(), 1001 , ABC, null, now(), now(), true)
( uuid_generate_v4(), 1002 , ABC, null, now(), now(), true)
( uuid_generate_v4(), 1003 , ABC, null, now(), now(), true)

For example, let's say the table has 5 unique orgIds (ABC, DEF, GHI, JKL, MNO) and for each of those orgs, I want to insert the above set of values. How would you combine the two query?

I think that you want:

insert into fforgs (id, ffid, orgid, value, enabled, createdat, updatedat)
select uuid_generate_v4(), f.ffId, o.orgId, null, now(), true
from (select distinct ffId from ffOrgs) o
cross join (values(1111, 1001, 1002, 1003)) f(orgId)

The query selects all distinct ffId from the table, then cross join s it with a fixed list of ordId values. The resulting dataset is inserted.

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