📜  SQL | AND和OR运算符

📅  最后修改于: 2021-05-19 20:01:03             🧑  作者: Mango

在SQL中,AND&OR运算符用于过滤数据并根据条件获得精确的结果。

  • AND和OR运算符与WHERE子句一起使用。
  • 这两个运算符称为合取运算符。

AND运算符:此运算符仅显示条件condition1和condition2都为True的那些记录

或运算符:此运算符显示条件1和条件2之一为“真”的记录。即, condition1为True或condition2为True。
表格1

AND运算符

基本语法:

SELECT * FROM table_name WHERE condition1 AND condition2 and ...conditionN;

table_name: name of the table
condition1,2,..N : first condition, second condition and so on

样本查询:

  1. 要从“学生”表中获取所有记录,其中“年龄”为18,“地址”为“德里”。
    SELECT * FROM Student WHERE Age = 18 AND ADDRESS = 'Delhi';
    

    输出:

    ROLL_NO NAME ADDRESS PHONE Age
    1 Ram Delhi XXXXXXXXXX 18
    4 SURESH Delhi XXXXXXXXXX 18
  2. 要从“学生”表中获取所有记录,其中“ NAME”是Ram,“ Age”是18。
    SELECT * FROM Student WHERE Age = 18 AND NAME = 'Ram';
    

    输出:

    ROLL_NO NAME ADDRESS PHONE Age
    1 Ram Delhi XXXXXXXXXX 18

或运算符

基本语法:

SELECT * FROM table_name WHERE condition1 OR condition2 OR... conditionN;

table_name: name of the table
condition1,2,..N : first condition, second condition and so on

样本查询:

  1. 要从Student表中获取所有记录,其中NAME是Ram或NAME是SUJIT。
    SELECT * FROM Student WHERE NAME = 'Ram' OR NAME = 'SUJIT';
    

    输出:

    ROLL_NO NAME ADDRESS PHONE Age
    1 Ram Delhi XXXXXXXXXX 18
    3 SUJIT ROHTAK XXXXXXXXXX 20
    3 SUJIT ROHTAK XXXXXXXXXX 20
  2. 要从Student表中提取所有记录,其中NAME是Ram或Age是20。
    SELECT * FROM Student WHERE NAME = 'Ram' OR Age = 20;
    

    输出:

    ROLL_NO NAME ADDRESS PHONE Age
    1 Ram Delhi XXXXXXXXXX 18
    3 SUJIT ROHTAK XXXXXXXXXX 20
    3 SUJIT ROHTAK XXXXXXXXXX 20

结合AND和OR

您可以按以下方式组合AND和OR运算符以编写复杂的查询。
基本语法:

SELECT * FROM table_name WHERE condition1 AND (condition2 OR condition3);

样本查询:

  1. 要从Student表中获取年龄为18 NAME的所有记录,NAME是Ram或RAMESH。
SELECT * FROM Student WHERE Age = 18 AND (NAME = 'Ram' OR NAME = 'RAMESH');

输出:

ROLL_NO NAME ADDRESS PHONE Age
1 Ram Delhi XXXXXXXXXX 18
2 RAMESH GURGAON XXXXXXXXXX 18