小编典典

字符串拆分列并连接到另一个表

sql

假设我有2个这样的表:

工作邀请:

+----+------------+------------+
| ID |    Name    | Categories |
+----+------------+------------+
|  1 | Programmer | 1,2        |
|  2 | Analyst    | 3          |
+----+------------+------------+

分类:

+----+-----------------+
| ID |      Name       |
+----+-----------------+
|  1 | Programming     |
|  2 | Web Programming |
|  3 | Analysis        |
+----+-----------------+

我们有一个字符串拆分,它接受一个字符串,一个定界符并返回一个表,我的问题是我真的不确定如何将表集成到查询中以加入工作机会和类别。

我的想法是这样的:

SELECT
    O.[ID]                  AS OfferID,
    O.[Name]                AS OfferName,
    CAT.[CategoryName]      AS CategoryName,
    CAT.[CategoryID]        AS CategoryID
FROM
    JobOffers AS O
LEFT JOIN
(
    SELECT 
        O.[ID]              AS OfferID,
        C.[CategoryID]      AS CategoryID,
        C.[Name]            AS Name
    FROM
        (
            SELECT *
            FROM [dbo].[Split](O.[Categories], ',')
        ) AS CJ
    LEFT JOIN
        [Categories] AS C
        ON C.CategoryID = CJ.items  
) AS CAT ON CAT.OfferID = O.[ID]

目前,我有两个错误的说法:

  • multi-part identifier O.[ID] cannot be bound
  • multi-part identifier O.[Categories] cannot be bound
  • incorrect syntax near AS (最后一行)

显然,问题是我如何构造子查询。


阅读 164

收藏
2021-03-17

共1个答案

小编典典

您可以将其简化为如下所示。

SELECT
    O.[ID]                  AS OfferID,
    O.[Name]                AS OfferName,
    c.[CategoryName]      AS CategoryName,
    c.[CategoryID]        AS CategoryID
FROM
    JobOffers AS O
outer apply [dbo].[Split](O.[Categories], ',') s
left join Categories as C on c.CategoryID = s.Items

我所关心的是您的分配器。如果有一个以上的select语句,那么性能将受到极大的影响。有关可用的各种分离器的良好说明,您可以访问本文。

http://sqlperformance.com/2012/07/t-sql-queries/split-
strings

2021-03-17