这或多或少与如何在使用 $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
如果你有想法会很棒,因为我一直在努力解决这个问题......