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_provider不存在于表customer_service_provider中但存在于service_provider表中的信息。

结果应如下所示:

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

解决了:

选择
    不同的 sp.id,
    csp.customer
从
    service_provider sp,
    customer_service_provider csp
在哪里
    sp.id 不在(选择 csp2.service_provider
                  FROM customer_service_provider csp2
                  其中 csp2.customer = csp.customer)
4

3 回答 3

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 JOIN在 customer_service_provider 表上执行此操作;并且只保留没有匹配记录的东西。

于 2012-05-18T08:24:30.720 回答
0
选择
    不同的 sp.id,
    csp.customer
从
    service_provider sp,
    customer_service_provider csp
在哪里
    sp.id 不在(选择 csp2.service_provider
                  FROM customer_service_provider csp2
                  其中 csp2.customer = csp.customer)
于 2012-05-21T13:20:29.253 回答