Combining 2 Queries to pull titles of 2 related content types from the node table Time to put our database hats on! We have a complex database call that responds to an AJAX request. We've omitted most of the code to just include the portion that is giving us trouble. We are working in Drupal 7.

  $products = "field_data_field_product_ref"; // table that contains the info about the product
  $productref = "field_product_ref_target_id"; // 

  // The following query prints the Title of our Object and the ID of the product it references

  $query = db_query ("Select n.nid AS nid, n.title AS title, p.$productref AS productid
  FROM {node} n
  INNER JOIN {$products} p ON p.entity_id = n.nid");


foreach ($query as $row) {
  print 'Swatch Title: '.$row-&gt;title.'&lt;br&gt;';
  print 'Product ID: '.$row-&gt;productid.'&lt;br&gt;&lt;br&gt;';

}


This outputs:
Swatch Title: Saddle Brown
Product ID: 19
Swatch Title: Sandalwood
Product ID: 20
Swatch Title: Saratoga
Product ID: 22

However, we want to also return the actual title of the product being referenced not its Product ID. A separate query can do this:

    $query = db_query ("Select n.nid AS pnid, n.title AS ptitle, p.entity_id AS productentityid
      FROM {node} n
      INNER JOIN {$products} p ON p.$productref = n.nid");

    foreach ($query as $row) {
      print 'Product Title: '.$row-&gt;ptitle.'&lt;br&gt;';
      print 'Swatch ID: '.$row-&gt;productentityid.'&lt;br&gt;&lt;br&gt;';

    }


Our second query's output:
Product Title: Slab
Swatch ID: 265
Product Title: Stone
Swatch ID: 184
Product Title: Brick
Swatch ID: 185

We would like the results to be:

Swatch Title: Saddle Brown
Product Title: Slab
Swatch Title: Sandalwood
Product Title: Stone
Swatch Title: Saratoga
Product Title: Brick

Can anyone clear up how to combine the 2 queries to get the intended output?
I think you just want to join the node table in to your query again and grab the title that way:

$query = db_query("
  SELECT n.nid AS pnid, n.title AS ptitle, n2.title as swatch_title
    FROM {node} n
    INNER JOIN {$products} p ON p.$productref = n.nid
    INNER JOIN {node} n2 ON n2.nid = p.$productref"
);