2011-07-04 74 views
2

我試圖從2個不同的表中得到一個顯示2列的結果集,分組由一列和求和。drupal 7 sql語法

這個SQL工作在phpMyAdmin:

SELECT SUM(field_count_value), field_region_value 
FROM field_data_field_count, field_data_field_region 
WHERE field_data_field_count.entity_id = field_data_field_region.entity_id 
GROUP BY field_data_field_region.field_region_value 
ORDER BY field_count_value DESC 

顯示大概正是我需要::

----------------- 
COUNT REGION 
----------------- 
4000  S 
600  E 
----------------- 

,但是當我將它轉換爲Drupal 7的SQL查詢語法:

$nodes = db_query("SELECT SUM(field_count_value), field_region_value 
FROM field_data_field_count, field_data_field_region 
WHERE field_data_field_count.entity_id = field_data_field_region.entity_id 
GROUP BY field_data_field_region.field_region_value 
ORDER BY field_count_value DESC"); 

foreach ($nodes as $record) { 
    echo $record->field_region_value . $record->field_count_value; 
    } 

我只能按列顯示:

----------------- 
REGION 
----------------- 
S 
E 
----------------- 

任何幫助將不勝感激。我已經諮詢了官方的d7文檔以獲得這麼多 - 不是很多的例子可以在那裏工作。

+0

對於你應該使用[EntityFieldQuery]這樣的查詢(http://api.drupal.org/ API/drupal的/包括 - entity.inc /類/ EntityFieldQuery/7)。 – kiamlaluno

回答

4

你需要做的

$nodes = db_query("SELECT SUM(field_count_value) AS field_count_value, field_region_value 
FROM field_data_field_count, field_data_field_region 
WHERE field_data_field_count.entity_id = field_data_field_region.entity_id 
GROUP BY field_data_field_region.field_region_value 
ORDER BY field_count_value DESC"); 

否則,第一列被稱爲 「SUM(field_count_value)」

+0

釘牢它,andreas - 不能夠感謝你。希望我能在幾小時前發佈! – wagner