/**
  * Get the query that matches a Fieldtype table's data with a given value
  *
  * Possible template method: If overridden, children should NOT call this parent method. 
  *
  * @param DatabaseQuerySelect $query
  * @param string $table The table name to use
  * @param string $subfield Name of the field (typically 'data', unless selector explicitly specified another)
  * @param string $operator The comparison operator
  * @param mixed $value The value to find
  * @return DatabaseQuery $query
  *
  */
 public function getMatchQuery($query, $table, $subfield, $operator, $value)
 {
     self::$getMatchQueryCount++;
     $n = self::$getMatchQueryCount;
     $field = $query->field;
     $database = $this->wire('database');
     $table = $database->escapeTable($table);
     if ($subfield === 'count' && (empty($value) || ctype_digit(ltrim("{$value}", '-'))) && in_array($operator, array("=", "!=", ">", "<", ">=", "<="))) {
         $value = (int) $value;
         $t = $table . "_" . $n;
         $c = $database->escapeTable($this->className()) . "_" . $n;
         $query->select("{$t}.num_{$t} AS num_{$t}");
         $query->leftjoin("(" . "SELECT {$c}.pages_id, COUNT({$c}.pages_id) AS num_{$t} " . "FROM " . $database->escapeTable($field->table) . " AS {$c} " . "GROUP BY {$c}.pages_id " . ") {$t} ON {$t}.pages_id=pages.id");
         if (in_array($operator, array('<', '<=', '!=')) && $value || in_array($operator, array('>', '>=')) && $value < 0 || in_array($operator, array('=', '>=')) && !$value) {
             // allow for possible zero values
             $query->where("(num_{$t}{$operator}{$value} OR num_{$t} IS NULL)");
             // QA
         } else {
             // non zero values
             $query->where("num_{$t}{$operator}{$value}");
             // QA
         }
         // only allow matches using templates with the requested field
         $sql = 'pages.templates_id IN(';
         foreach ($field->getTemplates() as $template) {
             $sql .= (int) $template->id . ',';
         }
         $sql = rtrim($sql, ',') . ')';
         $query->where($sql);
         // QA
     } else {
         $query = parent::getMatchQuery($query, $table, $subfield, $operator, $value);
     }
     return $query;
 }