-4

表结构..这里只有3个表..(购买,客户,产品)。..

bought table structure : fields (id,product_id,customer_id), 
customer table structure: (customer_id,name,address) , 
product table structure: (product_id,name). 

产品表内包括产品a和b。从购买的表中,我想获取客户 ID(购买了产品“a”但没有购买产品“b”的客户)。

使用 mysql 或类似的,你将如何选择所有购买了产品'a'但没有购买产品'b'的客户,而不使用子选择。(确保结果中没有客户购买产品'b'。)..请帮助我

4

3 回答 3

1

我不确定,您想按产品名称过滤吗?也许我在你的问题中遗漏了一些东西,但我认为这应该可行

select customer_id 
from
bought b
inner join customer c on b.customer_id = b.customer_id
inner join product p on p.product_id = b.product_id
where p.name = 'a'
于 2012-10-03T07:23:55.050 回答
0

这是您的表格和连接的全部答案。

顾客

CREATE TABLE customer (
  customer_id int NOT NULL PRIMARY KEY AUTO_INCREMENT,
  name varchar(50),
  address varchar(100)
) ENGINE=InnoDB;

产品

CREATE TABLE product (
  product_id int NOT NULL PRIMARY KEY AUTO_INCREMENT,
  name varchar(50)
) ENGINE = InnoDB;

购买或交易

CREATE TABLE bought (
  id int NOT NULL PRIMARY KEY AUTO_INCREMENT,
  product_id int,
  customer_id int,
  FOREIGN KEY (product_id) REFERENCES product(product_id),
  FOREIGN KEY (customer_id) REFERENCES customer(customer_id)
) ENGINE=InnoDB;

插入值

INSERT INTO customer (name, address) VALUEs ("George","Kentucky")
INSERT INTO customer (name, address) VALUEs ("Stan","Dublin")
INSERT INTO customer (name, address) VALUEs ("Kazaam","UAE")
INSERT INTO customer (name, address) VALUEs ("Sarah","New York")

INSERT INTO product (name) VALUES ("tomato")
INSERT INTO product (name) VALUES ("apple")

INSERT INTO bought (customer_id, product_id) VALUEs("1","2")
INSERT INTO bought (customer_id, product_id) VALUEs("2","1")
INSERT INTO bought (customer_id, product_id) VALUEs("3","1")
INSERT INTO bought (customer_id, product_id) VALUEs("4","1")

带过滤器的内部联接 --> 这将是您的 $query

SELECT customer.customer_id, customer.name as customer_name, product.name as product_name
FROM customer
INNER JOIN bought ON customer.customer_id = bought.customer_id
INNER JOIN product ON product.product_id = bought.product_id 
WHERE product.name LIKE "apple" AND product.name NOT LIKE "tomato"
ORDER BY customer.name

这将过滤所有购买苹果的客户。您所要做的就是更改product.name的值。如果要更改字段,请更改INNER JOIN的第一行。

维恩图的解释: 如果你仔细想想,MySQL是遵循维恩图的设计的。它不能与 3 个对象相交并过滤它们。您试图通过在中间构建另一个圆圈来超越维恩图的设计。见下图。

在此处输入图像描述

因此,为了解决您在 PHP 上的问题,我们创建了那个内圈。您运行一个循环来获取所有在 product_name 上有“apples”的 customer_id(s)。然后再次执行 mysql_fetch 数组的循环。并仅输出带有“apples”的 customer_ids。

如果用MySQL不能解决过滤,就用PHP过滤数据来解决。

于 2012-10-03T08:24:37.543 回答
0

我想吸引购买了产品“a”但没有购买产品“b”的客户

尝试这个:

SELECT * 
FROM Customers c
INNER JOIN
(
     SELECT * 
     FROM bought 
     WHERE product_id = id of 'a'
) ba ON c.CustomerId = ba.CustomerId
LEFT JOIN
(
     SELECT * 
     FROM bought 
     WHERE product_id = id of 'b'
) bb ON c.CustomerId = bb.CustomerId
WHERE bb.CustomerId IS NULL;
于 2012-10-03T07:28:00.377 回答