0

私は2つのテーブルを持っています:

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
======================

テーブルには存在しないがテーブルには存在するテーブルcustomer_service_provider(フィールドcustomerservice_provider)から情報を取得する必要があります。service_providercustomer_service_providerservice_provider

結果は次のようになります。

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

解決済み:

選択する
    DISTINCT sp.id、
    csp.customer
から
    service_provider sp、
    customer_service_provider csp
どこ
    sp.id NOT IN(SELECT csp2.service_provider
                  FROM customer_service_provider csp2
                  WHERE csp2.customer = csp.customer)
4

3 に答える 3

0
選択する
    DISTINCT sp.id、
    csp.顧客
から
    service_provider sp,
    customer_service_provider csp
どこ
    sp.id NOT IN( csp2.service_provider を選択
                  FROM customer_service_provider csp2
                  WHERE csp2.customer = csp.customer)
于 2012-05-21T13:20:29.253 に答える
0

これを試して:

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
)

または、より効率的です:

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

私はそれをテストしていません、私に知らせてください。

于 2012-05-18T08:19:53.767 に答える
0

あなたも顧客と一緒にテーブルを持っていると思います。その場合は、次を使用します。

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;

基本的に、顧客とサービス プロバイダーのすべての組み合わせを返します。LEFT JOINcustomer_service_provider テーブルでこれを行います。一致するレコードがないものだけを保持します。

于 2012-05-18T08:24:30.720 に答える