How can query table1 with a list of values for colA and get back the the list of the values that were not found?
i.e. all_values = ["a","b","c","d"]
Table1 already has rows with colA for "b","c"
I want to create a query that can I send in the entire all_values list and get back new_values = ["a","d"]
Currently I have to do this by first getting all existing_values = SELECT colA FROM table1
, then do new_values = all_values - existing_values at the application layer (ruby). But this can be an expensive routine if all_values grows very large. I want to leverage the db power here to tell me which values in my list don't exist already without needing to return first such a large list to the application layer.
[Solution] from David Faber's checked answer below, here is my solution from the application layer perspective (ruby on rails) in case anyone is interested. I've written the method so it can be included in any model you wish to use it on and accepts the column and list of values as arguments: [Update] parameterized the temp table name and setting datatype appropriately
def self.unfound_values_by_column values, column
quoted_values = values.collect {|value| "('#{value}')"}.join(",")
conn = self.connection # get this model's connection if different than base
temp_table_name = "temp_values_for_unfound_lookup_table"
datatype = self.columns_hash[column].sql_type
begin
conn.execute(
"DROP TEMPORARY TABLE IF EXISTS #{temp_table_name}"
)
conn.execute(
"CREATE TEMPORARY TABLE #{temp_table_name} (`#{column}` #{datatype})"
)
conn.execute(
"INSERT INTO #{temp_table_name} (#{column}) VALUES #{quoted_values}"
)
unfound = conn.select_values(
"SELECT temp.`#{column}` FROM `#{temp_table_name}` temp
WHERE NOT EXISTS (
SELECT 1 FROM `#{self.table_name}` my
WHERE my.`#{column}` = temp.`#{column}`
)"
)
ensure
conn.execute(
"DROP TEMPORARY TABLE IF EXISTS #{temp_table_name}"
)
end
unfound
end