我有一个由三个表组成的简单数据库:customer,product和custumer_product。
- 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
使用SQLITE
在sqlfiddle中初始化了三个表格。以下SQL查询用于构造数据库
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 customer_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 customer_product values(1,1);
insert into customer_product values(1,2);
insert into customer_product values(1,3);
insert into customer_product values(2,1);
insert into customer_product values(2,2);
insert into customer_product values(2,3);
insert into customer_product values(3,4);
insert into customer_product values(4,5);
insert into customer_product values(5,5);
对于每个客户,我想选择购买至少一个类似产品的所有其他客户。
"John" "Paul"
"Jenny"
"Fred" "Lea"
答案 0 :(得分:2)
这基本上是一个自连接,可能是一个聚合。例如,以下内容使所有购买了类似产品的客户得到了另类产品的排序,按照类似产品的数量排序:
select cp.id_customer, cp2.id_customer, count(*)
from customer_product cp join
customer_product cp2
on cp.id_product = cp2.id_product
group by cp.id_customer, cp2.id_customer
order by cp.id_customer, count(*) desc;
您可以通过执行其他连接来引入其他信息,例如客户名称。
答案 1 :(得分:1)
虽然我不完全确定我理解这些条件,但这个问题有三个基本步骤,您可以将它们合并为一个查询(或不合并)。
所以对于1,你做一个简单的选择:
SELECT id_product FROM customer_product WHERE id_customer = 1
对于2,您可以使用IN
语句:
SELECT * FROM customer_product WHERE id_product IN
(SELECT id_product FROM customer_product WHERE id_customer = 1);
3使用JOIN
和GROUP BY
的组合来获取customer
表中的相关详细信息。
答案 2 :(得分:0)
首先找到至少2个客户购买的产品列表,第二个找到使用连接表的客户名称,第三个选择客户的名称一次。这是查询:
select distinct c.name from(select c.name, p.name,cp.id_customer, cp.id_product from customer_product cp join customer c on c.id=cp.id_customer join product p on p.id=cp.id_customer where cp.id_product in(select id_product, total from(select id_product,count(*) as total from customer_product group by id_product)p where total>=2)p1)p2)