表结构....这里只有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'。)..请帮助我
答案 0 :(得分:0)
我不确定,您想按产品名称进行过滤吗?也许我在你的问题中遗漏了一些东西,但我认为这应该有用
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'
答案 1 :(得分: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;
答案 2 :(得分: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值
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")
内部加入过滤器 - &gt;这将是您的$查询
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。然后再次执行一个mysql_fetch数组循环。并仅使用“apples”输出customer_ids。
如果您无法通过MySQL解决过滤问题,请通过过滤数据来解决问题。