選擇用於替換這或多或少與此相關的How to preserve the order of the fields to be selected when using $query->addExpression()當使用工會佔位符似乎從初始值在工會
我在做什麼正在對多個表union
。但我也需要知道來自哪個表的值。所以我只是添加如下內容:$query->addExpression(':table', 'table_name', array(':table' => $table_name));
問題是,只要您創建聯合表名將被第一個查詢替換。
檢查下面的例子:
$table_name = 'table_one';
$query_1 = db_select('table_one', 't1');
$query_1->fields('t1', array('field_1', 'field_2'));
$query_1->addExpression(':table', 'table_name', array(':table' => $table_name));
$table_name = 'table_two';
$query_2 = db_select('table_two', 't2');
$query_2->fields('t2', array('field_1', 'field_2'));
$query_2->addExpression(':table', 'table_name', array(':table' => $table_name));
$table_name = 'table_three';
$query_3 = db_select('table_three', 't3');
$query_3->fields('t3', array('field_1', 'field_2'));
$query_3->addExpression(':table', 'table_name', array(':table' => $table_name));
如果我們檢查選擇單獨看起來都很好,你會得到預期的結果,但使用時,工會你只會看到table_one
所有的地方。
// dpq($query_1) - OK
SELECT t1.field_1 AS field_1, t1.field_2 AS field_2, 'table_one' AS table_name
FROM
{table_one} t1
// dpq($query_2) - OK
SELECT t2.field_1 AS field_1, t2.field_2 AS field_2, 'table_two' AS table_name
FROM
{table_two} t2
// dpq($query_3) - OK
SELECT t3.field_1 AS field_1, t3.field_2 AS field_2, 'table_three' AS table_name
FROM
{table_three} t3
// dpq($query_1->union($query_2)->union($query_3)) - OOPS.. 'table_one' all over the place
SELECT t1.field_1 AS field_1, t1.field_2 AS field_2, 'table_one' AS table_name
FROM
{table_one} t1 UNION SELECT t2.field_1 AS field_1, t2.field_2 AS field_2, 'table_one' AS table_name
FROM
{table_two} t2 UNION SELECT t3.field_1 AS field_1, t3.field_2 AS field_2, 'table_one' AS table_name
FROM
{table_three} t3
如果你有想法將是巨大的,因爲我一直在銀行我的頭與此一段時間...
,如果你嘗試'UNION ALL',而不是'UNION'? – arnoudhgz 2012-08-02 23:07:17
已經試過了,沒有什麼區別:('選擇t1.field_1 AS field_1,t1.field_2 AS呸ld_2,'table_one'AS table_name FROM {table_one} t1 UNION ALL SELECT t2.field_1 AS field_1,t2.field_2 AS field_2,'table_one'AS table_name FROM {table_two} t2 UNION ALL SELECT t3.field_1 AS field_1, t3.field_2 AS field_2,'table_one'AS table_name FROM {table_three} t3' – Max 2012-08-03 08:44:57