我有两个带有相关数据的表,我想从一个表中选择另一个表中不存在的所有记录,以及相关表上的一些其他条件,如下所示(123仅用于说明目的):
TABLE A ID SOMETHING TABLE B TABLE_A_ID TABLE_C_ID SOMETHING
我的查询直接针对数据运行,如下所示
SELECT A.SOMETHING FROM A WHERE A.ID NOT IN ( SELECT B.TABLE_A_ID AS ID FROM B WHERE TABLE_C_ID = 123 );
我如何在Zend中运行它?
您可以使用$db-> query();运行直接sql;你的只是:
$results = $db->query("SELECT A.SOMETHING FROM A WHERE A.ID NOT IN ( SELECT B.TABLE_A_ID AS ID FROM B WHERE TABLE_C_ID = ? )",$id);
编辑:要回答是否可以使用对象表示法,是:
$sub_select = $zdb->select() ->from("b",array("table_a_id AS id")) ->where("table_c_id = ?",'a'); $select = $zdb->select() ->from("a",array("something")) ->where("id NOT IN ?",$sub_select); print $select->__toString();
给
SELECT `a`.`something` FROM `a` WHERE (id NOT IN (SELECT `b`.`table_a_id` AS `id` FROM `b` WHERE (table_c_id = 'a')))