📜  SQL |像

📅  最后修改于: 2022-05-13 01:54:45.531000             🧑  作者: Mango

SQL |像

有时我们可能需要数据库中匹配某些模式的元组。例如,我们可能希望检索元组以字母“y”开头的所有列,或者以“b”开头并以“l”结尾的所有列,或者更复杂和限制性更强的字符串模式。这就是 LIKE 子句的用武之地,通常与 SQL 中的 WHERE 子句结合使用。

有两种通配符用于过滤掉结果:

  • %:用于匹配零个或多个字符。 (可变长度)
  • _:用于匹配一个字符。 (固定长度)

以下是使用 LIKE 子句进行模式匹配的规则:

PatternMeaning
‘a%’Match strings which start with ‘a’
‘%a’Match strings with end with ‘a’
‘a%t’Match strings which contain the start with ‘a’ and end with ‘t’.
‘%wow%’Match strings which contain the substring ‘wow’ in them at any position.
‘_wow%’Match strings which contain the substring ‘wow’ in them at the second position.
‘_a%’Match strings which contain ‘a’ at the second position.
‘a_ _%’Match strings which start with ‘a’ and contain at least 2 more characters.

例子:

假设我们有关系,供应商。我们想使用 LIKE 子句测试各种模式:

供应商表:

SupplierIDNameAddress
S1Paragon Suppliers21-3, Okhla, Delhi
S2Mango Nation21, Faridabad, Haryana
S3Canadian Biz6/7, Okhla Phase II, Delhi
S4Caravan Traders2-A, Pitampura, Delhi
S5Harish and SonsGurgaon, NCR
S6Om Suppliers2/1, Faridabad, Haryana

示例查询和输出:

SELECT SupplierID, Name, Address
FROM Suppliers
WHERE Name LIKE 'Ca%';

输出:

S3Canadian Biz6/7, Okhla Phase II, Delhi
S4Caravan Traders2-A, Pitampura, Delhi
SELECT *
FROM Suppliers
WHERE Address LIKE '%Okhla%';

输出:

S1Paragon Suppliers21-3, Okhla, Delhi
S3Canadian Biz6/7, Okhla Phase II, Delhi
SELECT SupplierID, Name, Address
FROM Suppliers
WHERE Name LIKE '_ango%';

输出:

S2Mango Nation21, Faridabad, Haryana

应用: LIKE运算符在地址过滤等情况下非常机智,在这种情况下,我们只知道整个地址的一部分或一部分(例如位置或城市),并希望基于此检索结果。可以根据需要充分利用通配符来产生更好和更多过滤的元组。