lundi 4 mai 2015

Select default value if no matched record

Take a table of the following structure:

ID, Email, Name

I am given a list of emails, and need to find out: which emails are present in the table as well as which ones are not. For those present, return the corresponding ID for each email.

I hope to achieve this using as few SQL statements as possible.

Two problems:

  1. Since I need to match each given email to an ID (if present), the order of the returned IDs must allow me to match them individually to given emails. If we do a simple SELECT ID FROM Table WHERE Email IN (...), the order of results may not match with the order of the list of emails given for the IN clause (at least for SQLite).

  2. A normal SELECT ... WHERE ... IN () statement also does not directly tell you which email are not present. I've tried the following in SQLite, while it runs, it doesn't give me what I want: SELECT COALESCE(ID, -1) AS UID, Email FROM Table WHERE Email IN (...): it returns only the matched records.

A naive solution is to run as many SELECT as the number of given emails, one for each, so that you know for each email if a record is present and if so what the ID is. But this may cause performance problem if the number of emails is large, especially when taking into account client-server communication overhead for SQL servers.

I am interested in a solution for SQLite as well as the equivalent for larger SQL servers.

Aucun commentaire:

Enregistrer un commentaire