5

我有一个名为accounts. 此表中有一个名为 的字段salesmanager_id。99% 的情况下,此字段中的值对于特定客户的所有帐户(用 指定customer_id)始终相同。

我想要做的是customer_id为客户分配给多个销售经理的客户。例如:

+------------------------------------+
| id | customer_id | salesmanager_id |
|------------------------------------|
| 1  | 12          | 4               |
| 2  | 12          | 4               |
| 3  | 14          | 3               | <-- I want this customer_id
| 4  | 14          | 4               |
+------------------------------------+

在上面的示例中,customer_id14 同时salesmanager_id分配了 3 和 4。我想customer_id为我的列表检索它。

我尝试了以下查询,但返回一个空结果(虽然我确信至少存在一些差异)。

SELECT `name`, `customer_id` AS `customer`, `salesmanager_id` FROM `accounts`
WHERE `salesmanager_id` NOT IN (
    SELECT `salesmanager_id` FROM `accounts` a
    LEFT JOIN `customers` c ON (a.customer_id = c.id)
    WHERE a.customer_id=c.id
) GROUP BY `customer`;
4

1 回答 1

13
SELECT 
    customer_id
FROM 
    accounts
GROUP BY 
    customer_id
HAVING 
    COUNT(DISTINCT salesmanager_id) > 1

这基本上得到了salesmanager_id每个的所有 s ,customer_id如果有多个唯一salesmanager_id值,customer_id则返回 。

于 2012-06-20T08:37:46.677 回答