SQL搜索包含第一个字符串

时间:2018-08-28 09:24:23

标签: sql sql-server sql-like

我有一个带有varchar列的表,如下所示:

    +---------+-----------+
    | FruitId | FruitName |
    +---------+-----------+
    |     123 | Apple     |
    |     123 | Mango     |
    |     145 | Mango     |
    +---------+-----------+

查询

select * from Fruits with (nolock) where FruitId  like '123 something something%'

预期结果:

123     Apple
123     Mango

查询

select * from Fruits with (nolock) where FruitName  like 'Apple something something%'

预期结果:

123     Apple

但是上面的查询不起作用,为什么?

任何帮助将不胜感激。

更新

select * from Fruits with (nolock) where FruitId  like '123 something something%' 
             or FruitName like 'Apple something something%'

即使这不起作用,希望我们必须将这两列连接起来。

5 个答案:

答案 0 :(得分:2)

如果我正确理解了您的问题,则应在如下所示的where子句中使用OR

查询#1

select * from Fruits with (nolock) where FruitId  like '123 Apple%'

应该是

select * from Fruits with (nolock) where FruitId  like '123' OR FruitName like 'Apple'

查询#2

select * from Fruits with (nolock) where FruitName  like 'Apple 123%'

应该像这样

select * from Fruits with (nolock) where FruitName  like 'Apple' OR FruitId like  '123'

答案 1 :(得分:1)

您可以通过将两列都连接起来来做到这一点

select * from Fruits with (nolock) where CONCAT(FruitId , ' ', FruitName ) 
         like '123 Apple%' OR CONCAT(FruitName , ' ', FruitId) like 'Apple 123%'

答案 2 :(得分:0)

尝试以下

DECLARE @T TABLE
(
    FruitId VARCHAR(50), 
    FruitName VARCHAR(50)
)
DECLARE @Src VARCHAR(50)='Apple 123'

INSERT INTO @T 
VALUES(123, 'Apple'),
(123, 'Mango'),
(145, 'Mango');

SELECT
    *
    FROM @T
        WHERE FruitId like LTRIM(RTRIM(SUBSTRING(@Src,1,CHARINDEX(' ',@Src))))+'%'
            OR
            FruitName like LTRIM(RTRIM(SUBSTRING(@Src,1,CHARINDEX(' ',@Src))))+'%'

答案 3 :(得分:0)

连接值以一次与LIKE进行比较:

CREATE TABLE fruits(FruitId VARCHAR(256), FruitName VARCHAR(256));
INSERT INTO fruits VALUES(123, 'Apple'),(123, 'Mango'),(145, 'Mango');

SELECT FruitId, FruitName 
FROM fruits 
WHERE FruitId+' '+FruitName like '123 Apple%' OR FruitName+' '+FruitId like '123 Apple%'

答案 4 :(得分:0)

尝试一下...

用户输入:123 something-something...

查询1

SELECT * 
FROM   fruits WITH (nolock) 
WHERE  '123 something-something...' LIKE Concat(fruitid, '%') 

结果

+---------+-----------+
| FruitId | FruitName |
+---------+-----------+
|     123 | Apple     |
|     123 | Mango     |
+---------+-----------+


用户输入:Apple something-something...

查询2

SELECT * 
FROM   fruits WITH (nolock) 
WHERE  'Apple something-something...' LIKE Concat(fruitname, '%') 

结果

+---------+-----------+
| FruitId | FruitName |
+---------+-----------+
|     123 | Apple     |
+---------+-----------+