views_query_alter Matching all values in IN clause I have a content type with a list(text) field. In which the admin can set multiple values on the field for the content type. Using a view the information is exposed to the end user. The views has a exposed filter to filter the list(text) field. However multiple options can be selected and need to be checked against the values set by the admin. The way Drupal views does this is by joining the table as many times as the amount of values being searched for, resulting in a very slow query.

I am now looking to do this with the query adjustment below inspired by this post:
https://stackoverflow.com/questions/11636061/matching-all-values-in-in-clause

However I have no clue on how to include the HAVING combined with COUNT as suggested in de post from the link above within Drupal. 

$field_values - array(1, 4)
$query-&gt;where[1]['conditions'][0]['field'] = 'field_data_field_listtext.field_data_field_listtext_value';
$query-&gt;where[1]['conditions'][0['value'] = $field_values;
$query-&gt;where[1]['conditions'][0['operator'] = 'IN';


Suggestions on solving the SQl query performance in other maners for exposed filters on list(text) are also very wecome.
The following code should allow you to add the SQL code found in the accepted answer to the S.O. post you mentioned to the Views generated SQL code.

function YOUR_MODULE_views_query_alter(&amp;$view, &amp;$query) {
    if ( $view-&gt;name == 'YOUR_VIEW_NAME' ) {
        $value_count = 0;

        // Collect the number of selected values in the exposed filter
        foreach($query-&gt;where[1]['conditions'] as $key =&gt; $condition) {
            if ( $condition['field'] == 'field_data_field_listtext.field_data_field_listtext_value' ) {
                $value_count = sizeof($query-&gt;where[1]['conditions'][$key]['value']);
                break; 
            }
        }

        // Add the having expression
        if( $value_count &gt; 0 ){
          $query-&gt;add_having_expression(
            0,
            "count(distinct :field_name) = :value_count", 
            array(
              ':field_name' =&gt; 'field_data_field_list_select.field_list_select_value', 
              ':value_count' =&gt; $value_count
            )
          );
        }
    }
}


Good luck!