Join SQL Server tables on a like statement

后端 未结 4 1257
失恋的感觉
失恋的感觉 2021-02-19 18:56

I am hoping this isn\'t a repeat. I\'ve checked the searches and I can\'t seem to find a clear answer to this.

I have a table that has it\'s primary key set to be a

相关标签:
4条回答
  • 2021-02-19 19:23

    Do you know that the = is always there and always is a UNIQUEIDENTIFIER. Then you can do this:

    WHERE CAST(SUBSTRING(URL, CHARINDEX('=',URL)+1,LEN(URL)) AS UNIQUEIDENTIFIER)=StateID
    

    EDIT

    As part of the comment you can also so it with a JOIN. Like this:

    select 
       u.* 
    from 
       urltable
    join statetable s 
       on CAST(SUBSTRING(URL, CHARINDEX('=',URL)+1,LEN(URL)) AS UNIQUEIDENTIFIER)=StateID
    
    0 讨论(0)
  • 2021-02-19 19:24

    Cast StateID to a compatible type, e.g.

    WHERE URL LIKE '%' + CONVERT(varchar(50), StateID) + '%'
    

    or

    WHERE URL LIKE N'%' + CONVERT(nvarchar(50), StateID) + N'%'
    

    if URL is nvarchar(...)

    EDIT

    As pointed out in another answer, this could result in poor performance on large tables. The LIKE combined with a CONVERT will result in a table scan. This may not be a problem for small tables, but you should consider splitting the URL into two columns if performance becomes a problem. One column would contain 'page.aspx?id=' and the other the UNIQUEIDENTIFIER. Your query could then be optimized much more easily.

    0 讨论(0)
  • 2021-02-19 19:29

    You may get a performance improvement if you build a temp table first, with the option to index the temp table. You could then also modify the schema (of your temp table) which could give you options on your join. Often when joining to BIG tables it helps to extract a subset of data to a temp table first, then join to it. Other times the overhead of the temp table is bigger than using an 'ugly' join

    0 讨论(0)
  • 2021-02-19 19:34
    select u.* from urltable
    join statetable s on url like N'%' + (convert(varchar(50),s.stateid) + N'%'
    

    performance is likely to be awful

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