Вопрос

I have 2 tables:

TABLE customer_service_provider
==================================
id   | customer | service_provider
==================================
1    | 1        | 1
2    | 1        | 2
3    | 1        | 3
4    | 2        | 1
5    | 2        | 2
6    | 3        | 1
7    | 4        | 1
8    | 4        | 2
9    | 4        | 3
===================================

TABLE service_provider
======================
id     | Name
======================
1      | Company1
2      | Company2
3      | Company3
======================

I need to get info from table customer_service_provider (fields customer and service_provider) which service_provider not exists in table customer_service_provider, but exist in service_provider table.

The result should look like:

customer   |  service_provider
==============================
2          | 3
3          | 2
3          | 3
==============================

SOLVED:

SELECT
    DISTINCT sp.id,
    csp.customer
FROM
    service_provider sp,
    customer_service_provider csp
WHERE
    sp.id NOT IN( SELECT csp2.service_provider 
                  FROM customer_service_provider csp2 
                  WHERE csp2.customer = csp.customer)
Это было полезно?

Решение

Try this:

SELECT c.customer, s.id
FROM customer_service_provider c, service_provider s
WHERE NOT EXISTS (
    SELECT * FROM customer_service_provider c2
    WHERE c2.customer = c.customer AND c2.service_provider = s.id
)

Or, more efficient:

SELECT c.customer, s.id
FROM customer_service_provider c, service_provider s
LEFT OUTER JOIN customer_service_provider c2 ON c2.customer = c.customer AND c2.service_provider = s.id
WHERE c2.id IS NULL

I've not tested it, let me know.

Другие советы

I presume you also have a table with customers. In that case, use the following:

select customer.id, service_provider.id 
from customer, service_provider 
left join customer_service_provider on customer.id=customer_service_provider.customer and service_provider.id=customer_service_provider.service_provider
where customer_service_provider.id IS NULL;

Basically, return all combinations of customers and service providers. Do a LEFT JOIN of this on the customer_service_provider table; and only keep things where there is no matching record.

SELECT
    DISTINCT sp.id,
    csp.customer
FROM
    service_provider sp,
    customer_service_provider csp
WHERE
    sp.id NOT IN( SELECT csp2.service_provider 
                  FROM customer_service_provider csp2 
                  WHERE csp2.customer = csp.customer)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top