I have a MySQL table called accounts. Within this table is a field called salesmanager_id. 99% of the time, the value in this field is always the same for all accounts of a specific customer (specified with customer_id).
What I’m trying to do is find the customer_id for the customers that have accounts assigned to more than one salesmanager. For example:
+------------------------------------+
| id | customer_id | salesmanager_id |
|------------------------------------|
| 1 | 12 | 4 |
| 2 | 12 | 4 |
| 3 | 14 | 3 | <-- I want this customer_id
| 4 | 14 | 4 |
+------------------------------------+
In the above example, customer_id 14 has both salesmanager_id 3 and 4 assigned to it. I would like to retrieve that customer_id for my list.
I tried the following query, but that returns an empty result (while I’m sure there are at least some differences).
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`;
This basically gets all of the
salesmanager_ids of eachcustomer_idand if there is more than one uniquesalesmanager_idvalue, thecustomer_idis returned.