mardi 3 novembre 2015

For every customer select all the other customers that bought the same item

Database description

I have a simple database composed of three tables: customer, product and custumer_product.

  • customer: Contains the information about the customer. His ID and name
  • product: Contains informations about the products that are available in the store. ID and name
  • custumer_product: junction table

- customer (table)
   id integer primary key not null
   name TEXT

- custumer_product (table)
   id_product integer
   id_customer integer
   primary key(id_product, id_customer)
   FOREIGN KEY(Id_product) REFERENCES product(id)
   FOREIGN KEY (ID_customer) REFERENCES customer(ID)

- product (table)
   id integer primary key not null
   name TEXT


The three tables have been initialized in sqlfiddle by using SQLITE. The following SQL queries are used to construct the database

create table if not exists customer (id integer primary key not null, name TEXT);
create table if not exists product  (id integer primary key not null, name TEXT);
create table if not exists custumer_product (id_product integer, id_customer 
integer, primary key(id_product, id_customer),  FOREIGN KEY(Id_product) REFERENCES product(id), FOREIGN KEY (ID_customer) REFERENCES customer(ID));

insert into customer(id,name)  values(1,"john");
insert into customer(id,name)  values(2,"Paul");
insert into customer(id,name)  values(3,"Jenny");
insert into customer(id,name)  values(4,"Fred");
insert into customer(id,name)  values(5,"Lea");

insert into product(id,name)  values(1,"Mouse");
insert into product(id,name)  values(2,"screen");
insert into product(id,name)  values(3,"pc");
insert into product(id,name)  values(4,"CD");
insert into product(id,name)  values(5,"Game");

insert into custumer_product values(1,1);
insert into custumer_product values(1,2);
insert into custumer_product values(1,3);

insert into custumer_product values(2,1);
insert into custumer_product values(2,2);
insert into custumer_product values(2,3);

insert into custumer_product values(3,4);
insert into custumer_product values(4,5);
insert into custumer_product values(5,5);


Problem

For every customer I want to select all the other customers that bought at least one similar product.

  • John and Paul bought at least 1 similar product
  • No customer bought a similar product as jenny yet
  • Fred and lea bought a similar product

output

"John" "Paul"
"Jenny"
"Fred" "Lea"

Aucun commentaire:

Enregistrer un commentaire