左联接不返回预期结果

时间:2020-10-27 19:55:34

标签: sql-server tsql

我有一张供应商(供应商)表:

+-----+-------------+--+
| ID  |   Vendor    |  |
+-----+-------------+--+
|   1 | ABC Company |  |
|   2 | DEF Company |  |
|   3 | GHI Company |  |
| ... | ...         |  |
+-----+-------------+--+

和服务表(AllServices):

+-----+------------+--+
| ID  |  Service   |  |
+-----+------------+--+
|   1 | Automotive |  |
|   2 | Medical    |  |
|   3 | Financial  |  |
| ... | ...        |  |
+-----+------------+--+

和一个链接这两个表(VendorServices):

+-----------+-----------+
| Vendor ID | ServiceID |
+-----------+-----------+
|         1 |         1 |
|         1 |         3 |
|         3 |         2 |
|       ... |       ... |
+-----------+-----------+

请注意,一家公司可能会提供多种服务,而有些公司可能不会提供任何列出的服务。

对于给定的供应商,我想要的查询结果将是

+------------+----------+
| Service ID | Provided |
+------------+----------+
|          1 |        0 |
|          2 |        0 |
|          3 |        1 |
|        ... |      ... |
+------------+----------+

列出了所有服务的位置,并且给定供应商提供的服务在“提供的”列中将为1,否则为零。

这是到目前为止我得到的:

SELECT
    VendorServices.ServiceID,
    <Some Function> AS Provided 
FROM
    AllServices LEFT JOIN VendorServices ON AllServices.ID = VendorServices.ServiceID
WHERE
    VendorServices.VendorID = @VendorID
ORDER BY
    Service

我有两个未知数:

  1. 上面的查询不会返回AllServices表中的每个条目;和
  2. 我不知道如何为Preovided列编写函数。

1 个答案:

答案 0 :(得分:2)

您需要将AllServicesVendorServices的LEFT连接和一个case表达式才能获得列provided

select s.id,
       case when v.serviceid is null then 0 else 1 end provided
from AllServices s left join VendorServices v
on v.serviceid = s.id and v.vendorid = @VendorID

请参见demo