在Zend Framework2中为同一个表写嵌套选择查询

时间:2017-06-22 13:24:13

标签: php sql-server zend-framework2

以下是我的查询

SELECT d.[today date], d.mydatediff,d.cc_exp
FROM (
    SELECT GETDATE() AS 'today date',
    cc_exp,
    DATEDIFF(DAY, CONVERT(DATE, DATEADD(DAY, -1, DATEADD(MONTH, 1, CONVERT(DATETIME, '1/' + cc_exp, 103)))), GETDATE()) AS mydatediff,
    [customer_member_id]
    FROM [ats].[dbo].[customers]
    WHERE cc_exp IS NOT NULL AND customer_member_id IN ('11111','2222','33333')
) d
WHERE d.mydatediff BETWEEN 30 AND 100
ORDER BY d.mydatediff DESC

我尝试创建两个SQL语句

$column = array(
    'dateDiff' => new Expression('DATEDIFF(DAY, CONVERT(DATE, DATEADD(DAY, -1, DATEADD(MONTH, 1, CONVERT(DATETIME, \'1/\' + cc_exp, 103)))), GETDATE())'), 
    'cc_exp',
    'customer_member_id'
);
$subselect = $sql->select();

$subselect->from(array('cus' => 'customers'));
$subselect->columns($column);
$where = new Where();
$where->in('customer_member_id', $memberId);
$where->and->isNotNull('cc_exp');
$subselect->where($where);

//$parent select
$select = $sql->select();
$select->from(array($subselect));
$selectColumn = array('cus.customer_member_id', 'cus.cc_exp', 'cus.dateDiff');
$where2 = new Where();
$where->between('cus.dateDiff','30','100');
$select->where($where2);

但它给了我一个错误

  

from()期望$ table作为数组是一个单元素关联数组

1 个答案:

答案 0 :(得分:0)

我可以在此代码中看到许多错误:

  • 您在子查询中定义cus别名,但在主查询中使用它
  • 您正在为主查询定义列列表,但之后却不使用它们
  • 您没有为子查询结果定义别名

尝试使用原始查询中使用的相同别名重构代码,这样可以更轻松地比较两者。然后我认为你的主要查询会有类似$select->from(array("d" => $subselect));这样的东西。