Finding Emails with Comma-Separated Values in MySQL
When working with MySQL tables containing comma-separated values (CSVs), searching for data can be challenging. For example, if you have a table with email addresses stored as CSVs, you may need to query it based on a specific email address.
Question:
A database consists of two tables: "customers" (containing customer email addresses) and "imap_emails" (containing "to" and "from" fields with CSV values). The goal is to fetch emails from the "customers" table and search for them in the "to" and "from" fields of the "imap_emails" table.
Solution using FIND_IN_SET:
One efficient way to perform such a search is by using the FIND_IN_SET function. This function returns the position of a specified string within a comma-separated list. By combining it with a join, you can achieve the desired result.
Example Query:
SELECT * FROM imap_emails INNER JOIN customers ON FIND_IN_SET(customers.email, imap_emails.to) > 0
This query performs an inner join between the "imap_emails" and "customers" tables based on the condition that the customer's email address exists in the "to" field of the "imap_emails" table (as determined by FIND_IN_SET).
Notes:
The above is the detailed content of How to Efficiently Search Comma-Separated Email Addresses in MySQL?. For more information, please follow other related articles on the PHP Chinese website!