Skip to content

Instantly share code, notes, and snippets.

@glyph
Last active May 14, 2024 04:20
Show Gist options
  • Save glyph/09f1d71c6329016b786cb75e62f20235 to your computer and use it in GitHub Desktop.
Save glyph/09f1d71c6329016b786cb75e62f20235 to your computer and use it in GitHub Desktop.
create table customer (
id integer primary key autoincrement,
name text not null
);
create table cupon (
id integer primary key autoincrement,
code text not null
);
create table customer_cupon_map (
customer_id integer not null,
cupon_id integer not null,
foreign key (customer_id) references customer(id),
foreign key (cupon_id) references cupon(id),
unique(customer_id,cupon_id)
);
insert into customer(name, id) values ('egon', 1001), ('dave', 2002), ('carol', 3003), ('bob', 4004), ('alice', 5005);
insert into cupon(code, id) values ('itsyourshow', 11), ('relayfm', 22), ('warmbo', 33), ('eatfresh', 44), ('morecodes', 55), ('bigweek', 66);
insert into customer_cupon_map(customer_id, cupon_id)
select customer.id, cupon.id from customer, cupon
where customer.name = 'alice' and cupon.code = 'itsyourshow';
select * from customer_cupon_map;
select '
-------
';
with
rowed_customer(custrow, custname, custid) as (
select (row_number() over (order by customer.name)), customer.name, customer.id
from customer
where not exists (select 1 from customer_cupon_map where customer_id = customer.id)
order by customer.name
),
rowed_cupon(cuprow, cupcode, cupid) as (
select (row_number() over (order by cupon.code)), cupon.code, cupon.id
from cupon
where not exists (select 1 from customer_cupon_map where cupon_id = cupon.id)
order by cupon.code
)
insert into customer_cupon_map
select custid, cupid from rowed_customer join rowed_cupon where custrow = cuprow;
select * from customer_cupon_map;
5005|11
-------
5005|11
4004|66
3003|44
2002|55
1001|22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment