【问题标题】:Zend_Db_Select: LEFT JOIN on a subselectZend_Db_Select: 左连接子选择
【发布时间】:2011-07-12 11:26:31
【问题描述】:

我有一个查询,它在子选择上执行LEFT JOIN。此查询在高负载环境中运行,并在设定的要求内执行。查询(高度简化)如下所示:

SELECT
  table_A.pKey
, table_A.uKey
, table_A.aaa
, table_B.bbb
, alias_C.ccc
, alias_C.ddd
FROM table_A
INNER JOIN table_B ON table_A.pKey = table_B.pKey
LEFT JOIN (

    SELECT
      table_X.pKey
    , table_X.ccc
    , table_Y.ddd
    FROM table_X
    INNER JOIN table_Y ON table_X.pKey = table_Y.pKey

  ) AS alias_C ON table_A.uKey = alias_C.pKey;

(由于各种原因,无法将子选择重写为(直接)LEFT JOIN)。

现在,我无法让 LEFT JOIN on subselectZend_Db_Select 一起使用。我已经尝试了所有我能想到的方法,但它不起作用。


所以我的问题是:

  • 是否无法使用Zend_Db_Select 进行上述查询?
  • 我需要什么语法才能让它在 Zend Framework 中工作?

【问题讨论】:

    标签: left-join zend-db subquery zend-db-select


    【解决方案1】:

    我认为它应该像这样工作:

    $subselect = $db->select->from(array('x' => 'table_X'), array('x.pKey', 'x.ccc', 'y.ddd'), 'dbname')
                            ->join(array('Y' => 'table_Y'), 'x.pkey = y.pkey', array(), 'dbname');
    
    $select = $db->select->from(array('a' => 'table_A'), array(/*needed columns*/), 'dbname')
                         ->join(array('b' => 'table_B'), 'a.pkey = b.pkey', array(), 'dbname')
                         ->joinLeft(array('c' => new Zend_Db_Expr('('.$subselect.')'), 'c.pkey = a.ukey', array())
    

    我没有尝试过,但我相信它会起作用。

    【讨论】:

    • 这是否意味着它需要实际执行 2 个查询?
    • 不,它会产生一个查询。 Zend_Db_Select 只是用于创建查询的流利包装器。它包含方法toSting()__toString()。您可以通过调用die($select) 之类的方法尝试一些调试,它会以您使用的数据库方言打印查询。
    • great new Zend_Db_Expr('('.$subselect.')') 是关键,在 Magento 上也非常有用!
    • 谢谢 - 非常有帮助 - 只是在最后一行的第一个数组中缺少右括号 - 它应该是:->joinLeft(array('c' => new Zend_Db_Expr('('.$subselect.')')), 'c.pkey = a.ukey', array()) - 无法编辑它,因为 SO 需要 > 6 个字符更改
    【解决方案2】:

    ... ->joinLeft(array('c' => new Zend_Db_Expr('(' . $subselect->assemble() . ')'), 'c.pkey = a.ukey', array())

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-08
      • 2018-06-23
      • 1970-01-01
      • 2016-11-13
      相关资源
      最近更新 更多