dtcaw02086 2016-08-17 13:43
浏览 38

如何在SQL中找到未找到哪些数据记录?

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;
     }
}
  • 写回答

2条回答 默认 最新

  • dqx13503925528 2016-08-17 13:47
    关注

    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'")
    
    评论

报告相同问题?