sql – Zend Framework:如何使用Joins在一个查询中组合三个表?

我有三个这样的表:

人员表:

person_id |    name     |   dob
--------------------------------
    1     |   Naveed    |  1988
    2     |   Ali       |  1985
    3     |   Khan      |  1987
    4     |   Rizwan    |  1984

地址表:

address_id |  street  |   city  |  state  | country
----------------------------------------------------
   1       | MAJ Road | Karachi |  Sindh  | Pakistan
   2       | ABC Road | Multan  |  Punjab | Pakistan
   3       | XYZ Road | Riyadh  |    SA   | SA

Person_Address表:

person_id | address_id
----------------------
   1      |     1
   2      |     2
   3      |     3

现在我想获取Person_Address表的所有记录,但也想通过一个查询获取这样的人员和地址记录:

person_id|    name  |  dob  | address_id |  street  |   city  |  state  | country
----------------------------------------------------------------------------------
    1    |   Naveed |  1988 |    1       | MAJ Road | Karachi |  Sindh  | Pakistan
    2    |   Ali    |  1985 |    2       | ABC Road | Multan  |  Punjab | Pakistan 
    3    |   Khan   |  1987 |    3       | XYZ Road | Riyadh  |    SA   | SA

如何使用zend?谢谢

最佳答案
参考指南是了解Zend_Db_Select的最佳起点.除了下面的例子,当然:

//$db is an instance of Zend_Db_Adapter_Abstract
$select = $db->select();
$select->from(array('p' => 'person'), array('person_id', 'name', 'dob'))
       ->join(array('pa' => 'Person_Address'), 'pa.person_id = p.person_id', array())
       ->join(array('a' => 'Address'), 'a.address_id = pa.address_id', array('address_id', 'street', 'city', 'state', 'country'));

然后就像获取一行一样简单:

$db->fetchRow($select);

在调试Zend_Db_Select时,你可以使用一个聪明的技巧 – 只需打印select对象,然后调用toString方法生成SQl:

echo $select; //prints SQL

转载注明原文:sql – Zend Framework:如何使用Joins在一个查询中组合三个表? - 代码日志