IN vs EXISTS dalam SQL: Memahami Prestasi dan Penggunaan

DDD
Lepaskan: 2024-09-14 06:19:37
asal
696 orang telah melayarinya

IN vs EXISTS in SQL: Understanding Performance and Usage

MySQL의 IN과 EXISTS: 실습 예제 및 설명

MySQL에서는 하위 쿼리의 행 존재 여부를 기준으로 데이터를 필터링하기 위해 쿼리에 IN과 EXISTS가 모두 사용됩니다. 그러나 이들은 서로 다른 방식으로 작동하며 둘 중 하나를 선택하면 쿼리 성능에 영향을 미칠 수 있습니다. 설명과 실제 사례를 통해 차이점을 살펴보겠습니다.


1. IN절

  • 설명:
    IN 절은 열의 값이 목록이나 하위 쿼리의 값과 일치하는지 여부에 따라 행을 필터링하는 데 사용됩니다. 내부 쿼리에서 일치하는 값을 확인하고 이를 외부 쿼리와 비교합니다.

  • 성능:
    IN 절은 일반적으로 하위 쿼리가 적은 수의 레코드를 반환할 때 효율적입니다. 그러나 하위 쿼리가 큰 데이터 세트를 반환하는 경우 IN이 느려질 수 있습니다.

  • 구문:

  SELECT columns 
  FROM table 
  WHERE column IN (subquery);
Salin selepas log masuk

2. EXISTS 조항

  • 설명:
    EXISTS 절은 하위 쿼리에서 반환된 행이 있는지 확인합니다. 하위 쿼리가 행을 반환하면 EXISTS는 TRUE로 평가되고 외부 쿼리가 진행됩니다. 행의 내용은 중요하지 않고 행의 존재 여부에만 관심이 있습니다.

  • 성능:
    EXISTS는 일치 항목을 찾으면 처리를 중지하므로 일반적으로 대규모 데이터 세트의 경우 더 빠릅니다. 이렇게 하면 많은 행을 반환하는 하위 쿼리로 작업할 때 효율적입니다.

  • 구문:

  SELECT columns 
  FROM table 
  WHERE EXISTS (subquery);
Salin selepas log masuk

실습 예시

고객과 주문이라는 두 개의 테이블을 생각해 보겠습니다.

고객 테이블:

customer_id customer_name
1 John Doe
2 Jane Smith
3 Alice Brown

주문표:

order_id customer_id order_total
1 1 200
2 1 150
3 2 300

We want to find all customers who have placed at least one order.


Using the IN Clause

SELECT customer_name 
FROM customers 
WHERE customer_id IN (SELECT customer_id FROM orders);
Salin selepas log masuk
Salin selepas log masuk

Explanation:

  • The subquery (SELECT customer_id FROM orders) returns all customer IDs that appear in the orders table.
  • The outer query selects customers whose customer_id is in that result set.

Result:
| customer_name |
|---------------|
| John Doe |
| Jane Smith |


Using the EXISTS Clause

SELECT customer_name 
FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id);
Salin selepas log masuk
Salin selepas log masuk

Explanation:

  • The subquery SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id checks whether any row in the orders table matches the customer_id of the current row from the customers table.
  • If any match is found, EXISTS returns TRUE, and the customer is included in the result.

Result:
| customer_name |
|---------------|
| John Doe |
| Jane Smith |


Key Differences

  1. Return Values:

    • IN: Compares the values of a column with the result set of the subquery.
    • EXISTS: Returns TRUE or FALSE based on whether the subquery returns any rows.
  2. Efficiency:

    • IN is more efficient for smaller datasets.
    • EXISTS is faster for large datasets, especially when the subquery returns many rows.
  3. Use Case:

    • Use IN when you're comparing a column’s value against a small list of possible values.
    • Use EXISTS when you're checking for the presence of rows in a subquery (e.g., when there's a correlation between the outer and inner queries).

Performance Example

Assume we have:

  • 10,000 customers
  • 100,000 orders

Query with IN:

SELECT customer_name 
FROM customers 
WHERE customer_id IN (SELECT customer_id FROM orders);
Salin selepas log masuk
Salin selepas log masuk
  • Execution: MySQL will retrieve the entire result set from the subquery and compare it with each row in the outer query.

Query with EXISTS:

SELECT customer_name 
FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id);
Salin selepas log masuk
Salin selepas log masuk
  • Execution: MySQL will check each row in the outer query and stop once it finds a matching row in the subquery, making it faster for large datasets.

Conclusion

  • Use IN when you have a simple list to compare or a small subquery result.
  • Use EXISTS when you’re dealing with large datasets or need to check for the presence of related data in a subquery.

Atas ialah kandungan terperinci IN vs EXISTS dalam SQL: Memahami Prestasi dan Penggunaan. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!