在LIKE mysql中搜索数组元素

时间:2013-07-25 11:48:50

标签: mysql arrays select stored-procedures sql-like

我有一个搜索类似下面的存储过程:

BEGIN
#At first, Search in name of job:
(SELECT * FROM tb_job WHERE `name` LIKE '%some%' AND `name` LIKE '%thing%')
UNION 
# second, search for tags:
(SELECT * FROM tb_job WHERE id IN 
    (
        SELECT idJob FROM
        (
            (SELECT 2 AS priority1, COUNT(tb_job_tag.idTag) AS priority2, idJob FROM tb_job_tag WHERE idTag IN
                (SELECT tb_tag.id FROM tb_tag WHERE tag LIKE '%some%' OR tag LIKE '%thing%')
            GROUP BY tb_job_tag.idJob)
        UNION
            (SELECT 1, COUNT(tb_job_tag.idTag), idJob FROM tb_job_tag WHERE idTag IN
                (SELECT tb_tag.id FROM tb_tag WHERE tag LIKE '%some%' AND tag LIKE '%thing%')
            GROUP BY tb_job_tag.idJob)
        )
        AS t ORDER BY priority1, priority2 DESC
    )
)

END

现在我有两个问题:我如何传递一个单词数组并将它们分开在mysql中并在LIKE中使用它们?第二,我怎样才能更好地进行搜索?

(我有3table:tb_job,tb_tag,tb_job_tag,用于存储作业的id和标签的id)。谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

/**
 * http://www.aspdotnet-suresh.com/2013/07/sql-server-split-function-example-in.html
 */
CREATE FUNCTION dbo.Array(@String nvarchar(4000), @Delimiter char(1))
RETURNS @Results TABLE ([id] [bigint] IDENTITY(1,1) NOT NULL, Items nvarchar(4000))
AS
BEGIN
    DECLARE @INDEX INT
    DECLARE @SLICE nvarchar(4000)
    -- HAVE TO SET TO 1 SO IT DOESNT EQUAL Z
    --     ERO FIRST TIME IN LOOP
    SELECT @INDEX = 1
    WHILE @INDEX !=0
    BEGIN
    -- GET THE INDEX OF THE FIRST OCCURENCE OF THE SPLIT CHARACTER
    SELECT @INDEX = CHARINDEX(@Delimiter,@STRING)
    -- NOW PUSH EVERYTHING TO THE LEFT OF IT INTO THE SLICE VARIABLE
    IF @INDEX !=0
    SELECT @SLICE = LEFT(@STRING,@INDEX - 1)
    ELSE
    SELECT @SLICE = @STRING
    -- PUT THE ITEM INTO THE RESULTS SET
    INSERT INTO @Results(Items) VALUES(@SLICE)
    -- CHOP THE ITEM REMOVED OFF THE MAIN STRING
    SELECT @STRING = RIGHT(@STRING,LEN(@STRING) - @INDEX)
    -- BREAK OUT IF WE ARE DONE
    IF LEN(@STRING) = 0 BREAK
    END
RETURN
END

在数据库中执行此功能一次,然后继续访问特定值,您可以编写查询,如下所示

 DECLARE @VALUE VARCHAR(100);
 SELECT TOP 1 @VALUE = Items FROM [dbo].[Array] ('some,thing,like,that' , ',') where id = 2
 PRINT @VALUE

您需要更改的所有内容都是select语句中的id。它现在只接受字符串值。但是您可以使用CAST

将SQL中的String转换为Int

如果您有任何建议/修改,我只是匆匆创建了这个功能让我知道......