2

我正在使用 Drupal 7,我必须在多个表上建立一个联合。要使工会工作,必须满足一些条件:

  1. 相同的列数
  2. 相同的数据类型
  3. 相同的顺序

一些表缺少一列,因此为了弥补这一点,我只需添加如下内容$query->addExpression(':field_1', 'field_1', array(':field_1' => NULL));:所以此时条件1&2都满足了,但是select中的字段顺序不同。

请参见下面的示例:

  $query_1 = db_select('table_one', 't1');
  $query_1->fields('t1', array('field_1', 'field_2'));

  $query_2 = db_select('table_two', 't2');
  if (true) {
    $query_2->fields('t2', array('field_1'));
  } else {
    $query_2->addExpression(':field_1', 'field_1', array(':field_1' => NULL));
  }
  $query_2->fields('t2', array('field_2'));        

  $query_3 = db_select('table_three', 't3');
  if (false) {
    $query_3->fields('t3', array('field_1'));
  } else {
    $query_3->addExpression(':field_1', 'field_1', array(':field_1' => NULL));
  }
  $query_3->fields('t3', array('field_2'));

结果是:

// dpq($query_1);
SELECT t1.field_1 AS field_1, t1.field_2 AS field_2
FROM {table_one} t1

// dpq($query_2);
SELECT t2.field_1 AS field_1, t2.field_2 AS field_2
FROM {table_two} t2

// dpq($query_3);
SELECT t3.field_2 AS field_2, '' AS field_1
FROM {table_three} t3

// dpq($query_1->union($query_2)->union($query_3));
SELECT t1.field_1 AS field_1, t1.field_2 AS field_2
FROM {table_one} t1 
UNION SELECT t2.field_1 AS field_1, t2.field_2 AS field_2
FROM {table_two} t2 
UNION SELECT t3.field_2 AS field_2, '' AS field_1
FROM {table_three} t3

似乎 using$query->addExpression不能保证该字段的位置是您期望的位置。addExpression查看已使用的第三个查询的转储。关于如何解决这个问题的任何想法?

4

2 回答 2

1

这是我发现保持订单的唯一解决方法。即使该字段存在与否,也要使用表达式。这样,订单就是您所期望的:

if (TRUE) {
  // To keep the order of the fields we have to use this hacky way.
  // Use a function that will not modify the string
  $query->addExpression("IFNULL(table_name.field_name, '')", 'field_name_alias');
} else {
  $query->addExpression(':field', 'field_name_alias', array(':field' => NULL));
}
于 2012-08-14T08:44:57.877 回答
0

我想添加一个简化的示例。为了保持字段的顺序而不是

$query->addField('n', 'uid', 'node_uid');

你可以写

$query->addExpression('n.uid', 'node_uid');
于 2020-03-16T05:40:28.117 回答