查找以下客户的customer_ID

ryevplcw  于 2022-10-22  发布在  Mysql
关注(0)|答案(3)|浏览(154)

我的代码是:

CREATE TABLE `table_a` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `value` varchar(255),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

CREATE TABLE `table_b` LIKE `table_a`;

INSERT INTO table_a VALUES (1, 'A'), (2, 'B'), (3, 'B');
INSERT INTO table_b VALUES (1, 'B');

SELECT value FROM table_a
INNER JOIN table_b
USING (value);
7y4bm7vi

7y4bm7vi1#

我将在此处使用聚合:

SELECT c.customer_ID 
FROM customer c
INNER JOIN transactions t
    ON t.customer_ID = c.customer_ID
INNER JOIN transaction_contains tc
    ON tc.transaction_ID = t.transaction_ID
INNER JOIN product p
    ON tc.UPC = p.UPC
WHERE
    p.brand IN ('Pepsi', 'Coca-Cola')
GROUP BY
    c.customer_ID
HAVING
    COUNT(DISTINCT p.brand) = 2;

请注意,我还使用了现代显式内部联接。

ve7v8dk2

ve7v8dk22#

像这样的事情应该马上就能做到。

SELECT
    DISTINCT(c1.Customer_ID)
FROM
    Customer c1
JOIN Transactions t ON t.Customer_ID = c1.Customer_ID
JOIN Contain c2 ON c2.Transaction_ID = t.Transaction_ID
JOIN Products p ON p.UPC = c2.UPC
WHERE
    p.Brand IN ('Pepsi', 'Coca-Cola');
c7rzv4ha

c7rzv4ha3#

您可以使用group by来实现这一点。如果您在IN中选择2个产品,那么您的计数必须是2。我使用了ANSI SQL标准语法进行连接

select  
  C1.customer_ID 
from 
  customer as C1 inner join 
  transactions as T1 on C1.customer_ID = T1.customer_ID  inner join 
  transaction_contains as T2 on T1.transaction_ID = T2.transaction_ID inner join
  product P on p.upc = T2.upc  
where 
  p.Brand IN ('Pepsi', 'Coca-Cola')
Group by 
  C1.customer_ID 
having 
  count(*) = 2

根据语法验证器检查语法

相关问题