📜  SQL – 逻辑运算符

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

SQL – 逻辑运算符

SQL 逻辑运算符用于测试条件的真实性。像比较运算符这样的逻辑运算符运算符返回布尔值TRUEFALSE 或未知。

下面给出了 SQL 中可用的逻辑运算符列表。

Operator Meaning
ANDTRUE if both Boolean expressions are TRUE.
INTRUE if the operand is equal to one of a list of expressions.
NOTReverses the value of any other Boolean operator.
ORTRUE if either Boolean expression is TRUE.
LIKETRUE if the operand matches a pattern.
BETWEENTRUE if the operand is within a range.
ALLTRUE if all of a set of comparisons are TRUE.
ANYTRUE if any one of a set of comparisons is TRUE.
EXISTSTRUE if a subquery contains any rows.
SOMETRUE if some of a set of comparisons are TRUE.

在下面的例子中,我们将看到这个逻辑运算符是如何工作的。

步骤 1:创建数据库 



为了创建数据库,我们需要使用 CREATE运算符。

询问:

CREATE DATABASE xstream_db;

第 2 步:创建表员工

在这一步中,我们将在 xstream_db 数据库中创建表employee。

询问:

CREATE TABLE employee (emp_id INT, emp_name VARCHAR(255), 
                                  emp_city VARCHAR(255),
                                  emp_country VARCHAR(255),
                                  PRIMARY KEY (emp_id));

为了在数据库中插入数据,我们需要使用 INSERT运算符。



询问:

INSERT INTO employee VALUES (101, 'Utkarsh Tripathi', 'Varanasi', 'India'),
                            (102, 'Abhinav Singh', 'Varanasi', 'India'), 
                            (103, 'Utkarsh Raghuvanshi', 'Varanasi', 'India'),
                            (104, 'Utkarsh Singh', 'Allahabad', 'India'),
                            (105, 'Sudhanshu Yadav', 'Allahabad', 'India'),
                            (106, 'Ashutosh Kumar', 'Patna', 'India');

输出:

现在下面给出的是逻辑运算符的一个例子。

AND 运算符

询问 :

SELECT * FROM employee WHERE emp_city = 'Allahabad' AND emp_country = 'India';

输出:

IN 运算符

询问:



SELECT * FROM employee WHERE emp_city IN ('Allahabad', 'Patna');

输出:

非运算符

询问:

SELECT * FROM employee WHERE emp_city NOT LIKE 'A%';

输出:

或运算符

询问:

SELECT * FROM employee WHERE emp_city = 'Varanasi' OR emp_country = 'India';

输出:

LIKE 运算符

询问:

SELECT * FROM employee WHERE emp_city LIKE 'P%';

输出:

BETWEEN 运算符

询问:

SELECT * FROM employee WHERE emp_id BETWEEN 101 AND 104;

输出:

ALL 运算符

询问:



SELECT * FROM employee WHERE emp_id = ALL 
                (SELECT emp_id FROM employee WHERE emp_city = 'Varanasi');

输出:

任何运营商

询问:

SELECT * FROM employee WHERE emp_id = ANY
                (SELECT emp_id FROM employee WHERE emp_city = 'Varanasi');

输出:

EXISTS 运算符

询问:

SELECT emp_name FROM employee WHERE EXISTS
                (SELECT emp_id FROM employee WHERE emp_city = 'Patna');

输出:

一些运营商

询问:

SELECT * FROM employee WHERE emp_id < SOME 
                (SELECT emp_id FROM employee WHERE emp_city = 'Patna');

输出: