SQL 搜索包含第一个字符串

SQL search contains first string

我有 table 和 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%'

即使这样也行不通,希望我们必须连接两列。

尝试以下方法

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))))+'%'

连接值以立即将两者与 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%'

如果我对你的问题的理解正确,你应该在你的 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'

您可以通过连接两列来完成此操作

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

试试这个...

用户输入: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     |
+---------+-----------+