1

I want a dynamic query to do inner join on same table.

My query is:

SELECT t1.table1 FROM table1 t1 INNER JOIN table2 t2 ON t1.id = t2.id AND t1.name = t2.name"

I want to join table1 and table2 based on id and name present in table2.

What is the equivalent dynamic query in Drupal for this? How this can be achieved?

1 Answer 1

1
$query = db_select('table1','t1');
$query->join('table2','t2','t1.id1=t2.id2');
$query->fields('t1', array('some fields'))
      ->fields('t2', array('some fields'));
$result = $query->execute()->fetchAll();

Then you can do print_r stuff into $result like

echo "<pre>";print_r($result);echo "</pre>";

If you have devel module installed and enabled, then you can also use:-

dsm($result);

This will give the whole result in form of array. If you need in form of object, then you need to modify few lines of code like this:-

$data = $result->execute();
while($result = $data->fetchObject()){
  //Do your related stuff
}

I think it will help a lot. Thanks.

8
  • Thanks @DeepakKumar. I want to join with name also. how to do the join with both of id and name in dynamic query? Jan 17, 2014 at 7:29
  • Please clear the question, I dont understand the dynamic query and both of id and name? I have some kind of foreign key present in both table right? then u need to apply join on it, that's it :) Jan 17, 2014 at 7:38
  • I want something like this. $query = db_select('table1','t1'); $query->join('table2','t2','t1.id1=t2.id2'); $query->join('table2', 't2, 't1.name=t2.name'); is it possible to join like this? Jan 17, 2014 at 7:45
  • @GanesanGopal yes, but every alias must be unique. You cannot have two t2 like do you now. db_select('table1', 't1'); $query->join('table2', 't2', '%alias.id2= t1.id1'); $query->join('table2', 't3', 't1.name=t2.name');
    – tenken
    Jan 17, 2014 at 7:50
  • @tenken yes every alias must be unique. I am referring the name field which is present in table2. So I think this query is right. Can u confirm? Jan 17, 2014 at 7:54

Not the answer you're looking for? Browse other questions tagged or ask your own question.