1

这或多或少与如何在使用 $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

如果你有想法会很棒,因为我一直在努力解决这个问题......

4

1 回答 1

0

睡了几个小时后,我追踪到了这个函数:

  // @file includes/database/select.inc
  public function arguments() {
    // ....

    // If there are any dependent queries to UNION,
    // incorporate their arguments recursively.
    foreach ($this->union as $union) {
      $args += $union['query']->arguments();
    }

    return $args;
  }

而且由于查询中的所有选择都具有相同的键:table,因此您最终只会得到一个参数而不是您。

解决方案:只要确保为占位符使用不同的键即可

因此,如果我们在上面的示例中替换这些行(注意:table_1&:table_2而不是:table

$query_2->addExpression(':table_1', 'table_name', array(':table_1' => $table_name));
$query_3->addExpression(':table_2', 'table_name', array(':table_2' => $table_name));

瞧,终于得到了预期的结果。希望它可以帮助某人,半天试图弄清楚为什么会发生这种情况。

SELECT t1.field_1 AS field_1, t1.field_2 AS field_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_two' AS table_name
FROM 
{table_two} t2 UNION ALL SELECT t3.field_1 AS field_1, t3.field_2 AS field_2, 'table_three' AS table_name
FROM 
{table_three} t3
于 2012-08-03T09:44:30.580 回答