-
-
Save glyph/09f1d71c6329016b786cb75e62f20235 to your computer and use it in GitHub Desktop.
created by https://github.com/tr3buchet/gister
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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