Advertising sustains the DA. Ads are hidden for members. Join today

Contributed module documentation

Views Display Union

Last updated on
15 June 2022

This module adds a Views display that uses a SQL UNION to combine one or more results sets with the results of a master display. This is useful when you need to logically OR two or more sets of results that have different contextual filters or use different relationships.

As an example, let's define a view using contextual filters which shows nodes that either have a title matching a user-defined value or were authored by a particular user. Begin by creating a new view, at /admin/structure/views/add:

Click Save and Edit.

Add a Contextual Filter. Choose Title:

Select Hide View and then Apply your change:

Add another Contextual Filter, this time Null:

The default configuration options do not need to be changed for the Null contextual filter.

Switch to the display called Page and then choose Duplicate as Union from the action menu.

This time we want to put the Null contextual filter in the first position. Begin by removing the Content: Title contextual filter. Then, add the Authored by filter, so that we can search by the author's user ID. Be sure to change the For dropdown to This union (override):

Under Advanced, click on Attach to: Not defined and choose the Page display:

Here's what the union display now looks like:

Switch back to the Page display and preview the view using an exact title from one of the nodes on your site, and the user ID of one of the users who has posted content:

If you have debugging options enabled and examine the query down below the preview, you'll see something like this, cleaned up a little to make it more readable:

SELECT "node_field_data"."created" AS "node_field_data_created", "node_field_data"."nid" AS "nid"
  FROM {node_field_data} "node_field_data"
  WHERE ("node_field_data"."title" = 'New question')
    AND ("node_field_data"."status" = '1')
UNION
SELECT "node_field_data"."created" AS "node_field_data_created", "node_field_data"."nid" AS "nid"
  FROM {node_field_data} "node_field_data"
  WHERE ((node_field_data.uid = '11'))
    AND ("node_field_data"."status" = '1')
ORDER BY "node_field_data_created" DESC
LIMIT 11 OFFSET 0;

Tags

Help improve this page

Page status: No known problems

You can: