📜  SQL |通配符运算符

📅  最后修改于: 2021-09-08 16:13:12             🧑  作者: Mango

先决条件:SQL | WHERE 条款
在上面提到的文章中讨论了 WHERE 子句,其中还解释了 LIKE运算符,您一定遇到过通配符这个词,现在让我们更深入地了解通配符。

通配符与 LIKE运算符运算符一起使用,有四种基本运算符:

Operator Description
% It is used in substitute of zero or more characters.
_ It is used in substitute of one character.
_ It is used to substitute a range of characters.
[range_of_characters] It is used to fetch matching set or range of characters specified inside the brackets.
[^range_of_characters] or [!range of characters] It is used to fetch non-matching set or range of characters specified inside the brackets.

基本语法:

SELECT column1,column2 FROM table_name WHERE column LIKE wildcard_operator;
column1 , column2: fields in the table
table_name: name of table
column: name of field used for filtering data

表格1

查询

  • 从学生表中获取名称以字母“T”结尾的记录。
    SELECT * FROM Student WHERE NAME LIKE '%T';
    

    输出:

    ROLL_NO NAME ADDRESS PHONE Age
    3 SUJIT ROHTAK XXXXXXXXXX 20
    3 SUJIT ROHTAK XXXXXXXXXX 20
  • 从学生表中获取名称以任何字母结尾但从“RAMES”开始的记录。
    SELECT * FROM Student WHERE NAME LIKE 'RAMES_';
    

    输出:

    2RAMESHGURGAONXXXXXXXXXX18

    ROLL_NO NAME ADDRESS PHONE Age
    2 RAMESH GURGAON XXXXXXXXXX 18
  • 从学生表中获取地址包含字母“a”、“b”或“c”的记录。
    SELECT * FROM Student WHERE ADDRESS LIKE '%[A-C]%';
    

    输出:

    2RAMESHGURGAONXXXXXXXXXX18

    ROLL_NO NAME ADDRESS PHONE Age
    2 RAMESH GURGAON XXXXXXXXXX 18
    2 RAMESH GURGAON XXXXXXXXXX 18
    3 SUJIT ROHTAK XXXXXXXXXX 20
    3 SUJIT ROHTAK XXXXXXXXXX 20
  • 从学生表中获取不包含字母“a”、“b”或“c”的 ADDRESS 记录。
    SELECT * FROM Student WHERE ADDRESS LIKE '%[^A-C]%';
    

    输出:

    ROLL_NO NAME ADDRESS PHONE Age
    1 Ram Delhi XXXXXXXXXX 18
    4 SURESH Delhi XXXXXXXXXX 18
  • 从学生表中获取记录,PHONE 字段的第 1 个位置为“9”,第 4 个位置为“5”。
    SELECT * FROM Student WHERE PHONE LIKE '9__5%';
    

    输出:

    ROLL_NO NAME ADDRESS PHONE Age
    1 Ram Delhi XXXXXXXXXX 18
  • 从 Student 表中获取包含总共 6 个字符的ADDRESS 的记录。
    SELECT * FROM Student WHERE ADDRESS LIKE '______';
    

    输出:

    ROLL_NO NAME ADDRESS PHONE Age
    3 SUJIT ROHTAK XXXXXXXXXX 20
    3 SUJIT ROHTAK XXXXXXXXXX 20
  • 从Student表中任意位置获取包含’OH’的ADDRESS记录,并且结果集不应包含重复数据。
    SELECT DISTINCT * FROM Student WHERE ADDRESS LIKE '%OH%';
    

    输出:

    ROLL_NO NAME ADDRESS PHONE Age
    3 SUJIT ROHTAK XXXXXXXXXX 20