I'm doing a search that tries to look for contacts with specified company names and job titles as the WHERE parameters. Sometimes there will not be any contacts with the specified job title and company. As I am using sets of company names how can I find out which results weren't found? This is really hard to explain...
An example SQL statement might be
SELECT *
FROM contacts
WHERE company_name IN ('bbc', 'yahoo', 'some company')
AND contact_position
LIKE 'manager'
I want to know which companies did not have any contacts for that job title, if that makes sense?
I have made this so far, but I presume there is a much better way of doing this:
$contacts_no_inv = Contact::find_query("
SELECT *
FROM contacts
WHERE {$data_search}
AND contact_position
LIKE '%{$_POST['job_title']}%'
");
if ($contacts_no_inv) {
foreach ($contacts_no_inv as $contact_no_inv) {
$companies_found[] = $contact_no_inv->company_name;
if (!in_array($contact_no_inv->contact_id, $idArr)) {
$filtered_no_inv[] = $contact_no_inv;
}
}
}
$companies_found = array_unique($companies_found);
$companies_found = array_filter($companies_found);
foreach ($_POST['query'] as $query) {
if (!in_array(strtolower($query), array_map('strtolower', $companies_found))) {
if (count(explode(' ', strtolower($query))) > 1) {
foreach (explode(' ', $query) as $query_element) {
if (!in_array(strtolower($query_element), array_map('strtolower', $companies_found))) {
$companies_found[] = $query;
}
}
}
$companies_not_found[] = $query;
}
}
Flip your WHERE
condition around to find things that don't match your existing condition. Like this
SELECT * FROM contacts WHERE company_name NOT IN ('bbc', 'yahoo', 'some company') OR contact_position NOT LIKE 'manager'")
One method is to switch the logic, as Gareth points out. Another is to just use NOT
:
SELECT c.*
FROM contacts c
WHERE NOT (company_name IN ('bbc', 'yahoo', 'some company') AND
contact_position LIKE 'manager'
);
A word of caution: both of these methods exclude NULL
values. So, if company_name
or contact_position
is NULL
, then neither method will return the row (NULL
comparisons return NULL
which is treated as false).