String split column and join to another table

后端 未结 3 1747
情话喂你
情话喂你 2021-01-02 02:08

Let\'s say I have 2 tables like this :

Job Offers:

+----+------------+------------+
| ID |    Name    | Categories |
+----+--------         


        
相关标签:
3条回答
  • 2021-01-02 02:31

    If you can live with one row per category then this will work:

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

    Re-aggregating them into a string is painful in SQL Server (but very possible).

    Note: you have a really, really bad data structure. So you should fix it as mentioned in a comment. Why is it bad?

    • You are storing numbers as strings.
    • You have ids that don't have a foreign key relationship to the reference table.
    • You are storing multiple values in a single field.
    0 讨论(0)
  • 2021-01-02 02:34

    From SQL SERVER 2016 we can use sql inbuilt function STRING_SPLIT as below :

    SELECT * FROM JobOffers as j 
    outer apply STRING_SPLIT(j.[Categories], ',') s
    left join dbo.Categories as c on c.CategoryID =s.value
    
    0 讨论(0)
  • 2021-01-02 02:37

    You can greatly simplify this to something like this.

    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
    

    The concern I have is your splitter. If there is more than a single select statement the performance is going to suffer horribly. For a good explanation of various splitters available you can visit this article.

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

    0 讨论(0)
提交回复
热议问题