简体   繁体   English

如何在Drupal视图中添加DISTINCT,GROUP BY子句

[英]How to add DISTINCT, GROUP BY clause in drupal view

I'm using drupal 6 and i've created a view and in view query i want to add 我正在使用drupal 6,我已经创建了一个视图,并且在视图查询中我想添加

GROUP BY AND DISTINCT CLAUSE. 分组和明确条款。

For that i tried to use views_groupby contributed module but it only provide COUNT SQL Aggregation Function. 为此,我尝试使用views_groupby贡献模块,但仅提供COUNT SQL聚合功能。

I don't know how to add group by clause and distinct clause in view query using hook_views_query_alter(&$view, &$query) . 我不知道如何使用hook_views_query_alter(&$view, &$query)在视图查询中添加group by子句和distinct子句。

So that it look like this - 这样看起来像这样-

SELECT DISTINCT(node.nid) AS nid, OTHER_COLUMN 
FROM TABLE_NAME 
JOIN ANOTHER_TABLE ON JOIN_CONDITION 
GROUP BY nid

Any help or suggestion would be greatly appreciated. 任何帮助或建议,将不胜感激。

Group By is not working on hook_views_query_alter and it is known as drupal views module issue. Group By在hook_views_query_alter上不起作用,这被称为drupal views模块问题。 which is reported at https://drupal.org/node/590534 , http://drupal.org/node/1608742 , http://drupal.org/node/389230#comment-2637200 该报道https://drupal.org/node/590534http://drupal.org/node/1608742http://drupal.org/node/389230#comment-2637200

Also views Aggregation Functions is not given desired result, because it will add all fields and sort order fields to group by criteria. 另外,视图聚合功能未获得期望的结果,因为它将添加所有字段并按标准对排序字段进行分组。 So, You should use other hooks such as hook_query_alter . 因此,您应该使用其他钩子,例如hook_query_alter

function hook_query_alter( &$query) {

  if($query->alterMetaData['view']->name == "your_views_name"){
     $query->groupBy("domain_source.domain_id");
     //also you can unset other group by critera by using, unset($query->getGroupBy());
  }
}

On your View edit form, under Basic Settings , try turning the Distinct setting on. 在“视图”编辑表单的“ 基本设置”下 ,尝试启用“ 区别”设置。

You may also try to use the Gear Icon for the Style section under Basic Settings . 您也可以尝试在基本设置下为样式部分使用齿轮图标 There you can specify a field to group by, if your row style is fields. 如果行样式是字段,则可以在此处指定要分组的字段。

function hook_views_query_alter(&$view, &$query) {
  if ($view->name == 'your_view_name') {
    $query->add_field('table', 'field', 'alias', array('function', groupby));
    $query->add_groupby('table.field');
  }
}

In Drupal 8, you will add "Group by" that way: 在Drupal 8中,您将以这种方式添加“分组依据”:

use Drupal\Core\Database\Query\AlterableInterface;

function MYMODULE_query_alter(AlterableInterface $query) {
  if (isset($query->alterMetaData['view'])) {
    if($query->alterMetaData['view']->id() == 'replace_by_view_machine_name') {
      // Group by UID to remove duplicates from View results
      $query->groupBy('users_field_data.uid');
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM