我正在使用 Drupal 7,我必须在多个表上建立一个联合。要使工会工作,必须满足一些条件:
- 相同的列数
- 相同的数据类型
- 相同的顺序
一些表缺少一列,因此为了弥补这一点,我只需添加如下内容$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
查看已使用的第三个查询的转储。关于如何解决这个问题的任何想法?