简体   繁体   English

Drupal中的数据库查询

[英]Database query in Drupal

So I have this sql code in Drupal: 所以我在Drupal中有以下sql代码:

$query = db_query('SELECT wpv.nid, n.title, AVG(vote) average FROM {wp_votes} wpv
    LEFT JOIN {node} n on wpv.nid = n.nid
    GROUP BY wpv.nid
    ORDER BY average DESC
    LIMIT 3');

It works just fine, but I need to write it with db_select: 它工作正常,但是我需要用db_select编写它:

$query2 = db_select('wp_votes','wpv');
$query2->join('node','n','wpv.nid = n.nid');
$query2->fields('wpv',array('nid','vote'));
$query2->fields('n',array('title'));
$rez = $query2->execute()->fetchAll();

My problem is that I don't know how I can get the average vote(votes are 1,2 or 3). 我的问题是我不知道如何获得平均投票(投票数为1,2或3)。 How do i rewrite the part with AVG(vote). 我该如何用AVG(投票)重写零件。 I tried with addEXpression('AVG(vote)') but it didn't work as expected, I got the average for all the entries, not just for those with the same id. 我尝试使用addEXpression('AVG(vote)'),但未按预期工作,我获得了所有条目的平均值,而不仅仅是具有相同ID的条目的平均值。

Thanks. 谢谢。

Seems that you forgot to use $query->groupBy('wpv.nid'); 似乎您忘记了使用$query->groupBy('wpv.nid');

that's why you got the AVG for all records. 这就是为什么您获得所有记录的AVG的原因。

For AVG you need to use addExpression() and groupBy and you will have something like this 对于AVG,您需要使用addExpression()和groupBy,您将获得类似这样的信息

<?php
$query2 = db_select('wp_votes','wpv');
$query2->join('node','n','wpv.nid = n.nid');
$query2->fields('wpv',array('nid','vote'));
$query2->fields('n',array('title'));
$alias = $query2->addExpression('AVG(vote)', 'average');
$query2->groupBy('wpv.nid');
$query2->sortBy($alias, 'DESC');
$rez = $query2->execute()->fetchAll();

I'm not sure about sorting by $alias, but theoretical, it should work. 我不确定要按$ alias进行排序,但理论上应该可以。

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

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