This article demonstrates several MySQL techniques for identifying phone calls from numbers not listed in a phone book database. We'll analyze the problem using sample data and provide efficient solutions.
Scenario:
We have two tables: Phone_book
and Call
.
Phone_book
Table:
<code>Phone_book +----+------+--------------+ | id | name | phone_number | +----+------+--------------+ | 1 | John | 111111111111 | +----+------+--------------+ | 2 | Jane | 222222222222 | +----+------+--------------+</code>
Call
Table:
<code>Call +----+------+--------------+ | id | date | phone_number | +----+------+--------------+ | 1 | 0945 | 111111111111 | +----+------+--------------+ | 2 | 0950 | 222222222222 | +----+------+--------------+ | 3 | 1045 | 333333333333 | +----+------+--------------+</code>
Goal: Find calls from phone numbers not in the Phone_book
table.
Solution Approaches:
Here are three effective methods to achieve this:
1. NOT IN
Clause:
This approach directly excludes phone numbers from the Call
table that are present in the Phone_book
table. It's efficient for smaller Phone_book
tables.
<code class="language-sql">SELECT * FROM Call WHERE phone_number NOT IN (SELECT phone_number FROM Phone_book);</code>
2. NOT EXISTS
Subquery:
This uses a subquery to check for the existence of a phone number in Phone_book
. It's generally more efficient than NOT IN
for larger Phone_book
tables.
<code class="language-sql">SELECT * FROM Call WHERE NOT EXISTS ( SELECT * FROM Phone_book WHERE Phone_book.phone_number = Call.phone_number );</code>
3. LEFT OUTER JOIN
:
This method employs a LEFT OUTER JOIN
to compare phone numbers. The query returns all calls, but only those with NULL
values in the Phone_book
columns represent unlisted numbers.
<code class="language-sql">SELECT * FROM Call LEFT OUTER JOIN Phone_book ON (Call.phone_number = Phone_book.phone_number) WHERE Phone_book.phone_number IS NULL;</code>
Choosing the Best Solution:
The optimal approach depends on your database's size and structure. For large datasets, the NOT EXISTS
subquery or LEFT OUTER JOIN
are usually preferred for better performance. For smaller datasets, the NOT IN
clause might be sufficient. Consider using EXPLAIN
to analyze query execution plans and choose the most efficient method.
The above is the detailed content of How to Find Calls from Numbers Not Listed in a Phone Book Database?. For more information, please follow other related articles on the PHP Chinese website!