There are two ways to use the IN operator for multiple fields in SQL: through a subquery or directly listing multiple values. Subqueries are used to retrieve values from other queries, while multiple values can be listed directly separated by commas. The IN operator checks whether a given value is in the list of specified values.
IN usage in multiple fields in SQL
IN operator is used to check whether a given value is in in a list of specified values. When you need to check multiple fields, you can use a subquery or multiple values in the IN operator.
Subquery
A subquery is a nested query used to retrieve data from a database. It can be used within the IN operator to compare the values of multiple fields against it. The syntax is as follows:
<code class="sql">SELECT * FROM table_name WHERE (column1, column2, ...) IN ( SELECT column1, column2, ... FROM subquery );</code>
For example:
<code class="sql">SELECT * FROM orders WHERE (order_id, customer_id) IN ( SELECT order_id, customer_id FROM order_details );</code>
Multiple values
You can also specify multiple values in the IN operator, separated by commas. The syntax is as follows:
<code class="sql">SELECT * FROM table_name WHERE (column1, column2, ...) IN (value1, value2, ...);</code>
For example:
<code class="sql">SELECT * FROM customers WHERE (first_name, last_name) IN ('John', 'Doe');</code>
Example
Consider a table containing the following dataorders
:
order_id | customer_id | product_id |
---|---|---|
1 | 201 | |
1 | 301 | |
2 | 201 | |
2 | 302 |
<code class="sql">SELECT * FROM orders WHERE (product_id) IN (201, 302);</code>The output will be:
customer_id | product_id | |
---|---|---|
1 | 201 | |
1 | 301 | |
2 | 201 | ##104 |
302 |
The above is the detailed content of Usage of multiple fields in sql. For more information, please follow other related articles on the PHP Chinese website!