需要查找哪些客户正在使用产品1和2,而尚未使用产品3
请检查以下mysql数据
mysql> select product,customer from test1 where product in (1,2,3);
+------+------+
| product | customer |
+------+------+
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 1 | 4 |
| 1 | 5 |
| 1 | 6 |
| 1 | 7 |
| 1 | 9 |
| 1 | 8 |
| 2 | 1 |
| 2 | 3 |
| 2 | 4 |
| 2 | 6 |
| 2 | 7 |
| 2 | 8 |
| 2 | 9 |
| 3 | 4 |
| 3 | 5 |
| 3 | 6 |
+------+------+
19 rows in set (0.00 sec)
有相当多的方法来做到这一点,效率将根据您的索引而有所不同。 一种简单的方法是使用连接。 您可以使用内部联接将表与其自身联接,以获取拥有一个以上产品的客户,然后使用外部联接以确保客户没有其他产品。
下面是一个代码片段:
SELECT customersWithProduct1.customer
FROM
test1 customersWithProduct1
INNER JOIN test1 customersWithProduct2 ON customersWithProduct1.customer = customersWithProduct2.customer
LEFT OUTER JOIN test1 customersWithProduct3 ON customersWithProduct1.customer = customersWithProduct3.customer AND customersWithProduct3.product = 3
WHERE
customersWithProduct1.product = 1
AND customersWithProduct2.Product = 2
AND customersWithProduct3.customer IS NULL