Write a sub query by db_select drupal7

$table  = self::getPropertyTableName($campaign_code, $activity_code);
$sub_query  = db_select($table, ‘p’)->fields(‘p’, array(‘activity_id’));
$sub_query->addExpression(‘max(p.changed)’, ‘max_changed’);
foreach ((array)$values as $field_name => $field_value) {
$sub_query->condition(‘p.’.$field_name, $field_value);
}
$sub_query->groupBy(‘activity_id’);

$query = db_select($table, ‘a’)->fields(‘a’, array());
$query->orderBy(‘a.changed’, ‘DESC’);

$query->join($sub_query, ‘p’, ‘p.activity_id=a.activity_id AND p.max_changed=a.changed’);

$row = $query->execute()->fetchAll();

if ($row) {
$properties = $row;
}

Advertisements

One thought on “Write a sub query by db_select drupal7

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s