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

📅  最后修改于: 2021-08-27 17:57:11             🧑  作者: 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.