SQL Array Search

前端 未结 4 1548
悲&欢浪女
悲&欢浪女 2021-01-26 05:45

I have a group feature on my website that allows 1 user to put the userids of any of his or her friends into an invitedusers column. I need to do an SQL search to determine whet

4条回答
  •  清酒与你
    2021-01-26 06:28

    You may not want to store a comma delimited list in a column, but since you are:

    SELECT userid, name FROM mytable
    WHERE invitedusers = '(' + '234' + ')' -- One and only one entry
    OR invitedusers LIKE '(' + '234' + ',%' -- First entry
    OR invitedusers LIKE '%,' + '234' + ',%' -- Middle entry
    OR invitedusers LIKE '%,' + '234' + ')%' -- Last entry
    

    I have modified based on EBarr's comment. There are four cases to check for. This assumes you are storing the data with a ( prefix and a ) suffix and separating everything with commas.

    Here are some tests to prove that it works:

    /* Tests */
    INSERT INTO @mytable SELECT 11, 'a', '(234)' -- Should get returned
    INSERT INTO @mytable SELECT 12, 'b', '(1234)'
    INSERT INTO @mytable SELECT 13, 'c', '(92349)'
    INSERT INTO @mytable SELECT 13, 'd', '(2345)'
    
    INSERT INTO @mytable SELECT 21, 'a', '(234,567)' -- Should get returned
    INSERT INTO @mytable SELECT 22, 'b', '(1234,567)'
    INSERT INTO @mytable SELECT 23, 'c', '(92349,567)'
    INSERT INTO @mytable SELECT 23, 'd', '(2345,567)'
    
    INSERT INTO @mytable SELECT 31, 'a', '(567,234)' -- Should get returned
    INSERT INTO @mytable SELECT 32, 'b', '(567,1234)'
    INSERT INTO @mytable SELECT 33, 'c', '(567,92349)'
    INSERT INTO @mytable SELECT 33, 'd', '(567,2345)'
    
    INSERT INTO @mytable SELECT 41, 'a', '(123,234,789)' -- Should get returned
    INSERT INTO @mytable SELECT 42, 'b', '(123,1234,789)'
    INSERT INTO @mytable SELECT 43, 'c', '(123,92349,789)'
    INSERT INTO @mytable SELECT 43, 'd', '(123,2345,789)'
    
    SELECT userid, name FROM @mytable
    WHERE invitedusers = '(' + '234' + ')' -- One and only one entry
    OR invitedusers LIKE '(' + '234' + ',%' -- First entry
    OR invitedusers LIKE '%,' + '234' + ',%' -- Middle entry
    OR invitedusers LIKE '%,' + '234' + ')%' -- Last entry
    

提交回复
热议问题