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

时间:2015-10-09 15:59:34

标签: sql sql-server

我们说我有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(最后一行)

问题很清楚我是如何构建子查询的。

3 个答案:

答案 0 :(得分:11)

你可以大大简化这个。

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

答案 1 :(得分:3)

在SQL SERVER 2016中,我们可以使用sql内置函数STRING_SPLIT 如下:

SELECT * FROM JobOffers as j 
outer apply STRING_SPLIT(j.[Categories], ',') s
left join dbo.Categories as c on c.CategoryID =s.value

答案 2 :(得分:2)

如果每个类别可以使用一行,那么这将有效:

select jo.*, c.name as category
from joboffers jo join
     categories c
     on ',' + jo.categories + ',' like '%,' + cast(c.id) + ',%';

将它们重新聚合成一个字符串在SQL Server中很痛苦(但很可能)。

注意:您的数据结构非常非常糟糕。所以你应该像评论中提到的那样修复它。为什么不好?

  • 您将数字存储为字符串。
  • 您的ID与参考表没有外键关系。
  • 您将多个值存储在一个字段中。