📜  SQL中=和IN运算符的区别

📅  最后修改于: 2021-09-10 01:24:12             🧑  作者: Mango

先决条件 – SQL 命令
在本文中,我们将看到 SQL 中 = 和 IN运算符之间的区别。

1. = 运算符:
=运算符与 SQL 中的 Where 子句一起使用。
例如考虑下面给出的学生表,

ROLL_NO NAME ADDRESS PHONE Age
1 Ram Delhi xxxxxxxxxx 18
2 RAMESH GURGAON xxxxxxxxxx 18
3 SUJIT ROHTAK xxxxxxxxxx 20
4 SURESH Delhi xxxxxxxxxx 18
3 SUJIT ROHTAK xxxxxxxxxx 20
2 RAMESH GURGAON xxxxxxxxxx 18

询问 :
获取地址为Delhi 或ROHTAK 的学生记录。
使用 =运算符的 SQL 查询将是,

SELECT * 
FROM Student 
WHERE ADDRESS='Delhi' OR ADDRESS='ROHTAK'; 

输出 :

ROLL_NO NAME ADDRESS PHONE Age
1 Ram Delhi xxxxxxxxxx 18
3 SUJIT ROHTAK xxxxxxxxxx 20
4 SURESH Delhi xxxxxxxxxx 18
3 SUJIT ROHTAK xxxxxxxxxx 20

2. IN 运营商:
IN运算符与 Where 子句一起使用以测试表达式是否与值列表中的任何值匹配。使用 IN运算符的优点是避免使用多个 OR 运算符。

询问 :
获取地址为Delhi 或ROHTAK 的学生记录。
使用 IN运算符的 SQL 查询将是,

SELECT * 
FROM Student 
WHERE ADDRESS IN ('Delhi', 'ROHTAK'); 

输出 :

ROLL_NO NAME ADDRESS PHONE Age
1 Ram Delhi xxxxxxxxxx 18
3 SUJIT ROHTAK xxxxxxxxxx 20
4 SURESH Delhi xxxxxxxxxx 18
3 SUJIT ROHTAK xxxxxxxxxx 20

= 和 IN 运算符的区别:

= Operator IN Operator
It allows comparison of attributes with single value. It allows comparison of attributes with multiple value. For single value comparison behaves same as = .
For multiple comparison we have to use appropriate Operator in addition.(i.e JOIN, OR, AND, etc.) No additional use of Operator required.
Useful in scenarios when sub-query returns single value as result. Useful in scenarios when sub-query returns multiple values as result.
It will generate an error if you have more than one result on the subquery. It will not generate an error if you have multiple results on the subquery.
It is faster as compared to IN Operator. The IN clause is slower compared to = as it compares with multiple values until the condition satisfies.