这是您的表格和连接的全部答案。
顾客
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过滤数据来解决。