How do I properly combine UNION with LIMIT?

I’m trying to get content from database divided by category. I want strictly max 4 entries of type “people” and 4 other entries of type “organization”.

I tried to do it like that:

$query = db_select('node', 'n') ->fields('n', array('title','type')) ->fields('i', array('field_image_fid')) ->fields('f', array('uri')) ->condition('n.title', '%'. db_like($keys) . '%', 'LIKE') ->condition('type', array('people')) ->range(0,4); $query->leftJoin('field_data_field_image', 'i', 'i.entity_id = n.nid'); $query->leftJoin('file_managed', 'f', 'f.fid = i.field_image_fid');  $query2 = db_select('node', 'n') ->fields('n', array('title','type')) ->fields('i', array('field_image_fid')) ->fields('f', array('uri')) ->condition('n.title', '%'. db_like($keys) . '%', 'LIKE') ->condition('type', array('organization')) ->range(0,4); $query2->leftJoin('field_data_field_image', 'i', 'i.entity_id = n.nid'); $query2->leftJoin('file_managed', 'f', 'f.fid = i.field_image_fid');  $query->union($query2, 'UNION'); $result = $query ->execute(); 

The problem is that this query is returning only the first 4 occurrences of people or organization combined. So if there are 4 people returned by the query, I will not be able to see any organization.

I also tried something like this:

    $query = db_query('          SELECT p.title,p.type              FROM node as p             WHERE p.type = :type              LIMIT 4'         , array(':type' => 'people',':type1' => 'organization'))->fetchAll();  $query2 = db_query('          SELECT o.title,o.type              FROM node as o             WHERE o.type = :type1              LIMIT 4'         , array(':type' => 'people',':type1' => 'organization'))->fetchAll();   $query->union($query2, 'UNION'); 

or like this:

$result = db_query('      SELECT title,type          FROM {node}          WHERE type = :type          LIMIT 4      UNION ALL     SELECT title,type          FROM {node}          WHERE type = :type1          LIMIT 4'     , array(':type' => 'people',':type1' => 'organization'))->fetchAll(); 

But these two approaches are only returning the 4 people and no organizations, I mean never..

Thank you if you can help!

——————–EDIT——————–

Thank you for your comment Clive. I hadn’t tried yet to do it directly in plain SQL.

The query is something like that

(SELECT title,type FROM node WHERE type = 'organization'  LIMIT 4)  UNION (SELECT  title,type FROM node WHERE type = 'people'  LIMIT 4)  

I didn’t know but the parentheses are necessary to act as I need. Like that I get 4 of each, then 8 maximum in total.

So the same in drupal using db_query is something like:

$result = db_query('  (SELECT title,type      FROM {node}      WHERE type = :type      LIMIT 4 ) UNION ALL (SELECT title,type      FROM {node}      WHERE type = :type1      LIMIT 4)' , array(':type' => 'people',':type1' => 'organization'))->fetchAll(); 

I don’t know if it’s possible to do the same with db_select

————–EDIT2—————————

Regarding to Molot comments, I changed my query to:

    $subquery_1 = db_select('node', 'n')     ->fields('n', array('title','type'))     ->fields('i', array('field_image_fid'))     ->fields('f', array('uri'))     ->condition('n.title', '%'. db_like($keys) . '%', 'LIKE')     ->condition('type', array('people'))     ->range(0,3);     $subquery_1->leftJoin('field_data_field_image', 'i', 'i.entity_id = n.nid');     $subquery_1->leftJoin('file_managed', 'f', 'f.fid = i.field_image_fid');      $subquery_2 = db_select('node', 'n')     ->fields('n', array('title','type'))     ->fields('i', array('field_image_fid'))     ->fields('f', array('uri'))     ->condition('n.title', '%'. db_like($keys) . '%', 'LIKE')     ->condition('type', array('organization'))     ->range(0,5);     $subquery_2->leftJoin('field_data_field_image', 'i', 'i.entity_id = n.nid');     $subquery_2->leftJoin('file_managed', 'f', 'f.fid = i.field_image_fid');      $query = $subquery_1->union($subquery_2);     $f->fb((string)$query);     $result = $query   ->execute(); 

Now the query return People and Organizations together and limited to 5. Here is the print of the query:

SELECT n.title AS title, n.type AS type, i.field_image_fid AS field_image_fid, f.uri AS uri FROM {node} n LEFT OUTER JOIN {field_data_field_image} i ON i.entity_id = n.nid LEFT OUTER JOIN {file_managed} f ON f.fid = i.field_image_fid WHERE (n.title LIKE :db_condition_placeholder_0 ESCAPE '\') AND (type IN (:db_condition_placeholder_1)) LIMIT 3 OFFSET 0 UNION SELECT n.title AS title, n.type AS type, i.field_image_fid AS field_image_fid, f.uri AS uri FROM {node} n LEFT OUTER JOIN {field_data_field_image} i ON i.entity_id = n.nid LEFT OUTER JOIN {file_managed} f ON f.fid = i.field_image_fid WHERE (n.title LIKE :db_condition_placeholder_2 ESCAPE '\') AND (type IN (:db_condition_placeholder_3)) LIMIT 5 OFFSET 0 
This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

How do I properly combine UNION with LIMIT?

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.