Zend Select NOT IN

馋奶兔 提交于 2019-11-30 04:22:35

问题


I have two tables with related data, and I want to select all the records from one table which do not exist in the other table, plus some other criteria on the related table, as follows (123 is just for illustration purposes):

TABLE A
    ID
    SOMETHING

TABLE B
    TABLE_A_ID
    TABLE_C_ID
    SOMETHING

My query, run directly against the data, would be as follows

SELECT A.SOMETHING 
    FROM A 
    WHERE A.ID NOT IN (
        SELECT 
            B.TABLE_A_ID AS ID 
            FROM B 
            WHERE TABLE_C_ID = 123
    );

How can I run this in Zend?


回答1:


You can run direct sql, using $db->query(); yours would simply be:

$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);

EDIT: To answer whether this can be done with the object notation, yes:

$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();

gives

SELECT `a`.`something` FROM `a`
WHERE (id NOT IN
    (SELECT `b`.`table_a_id` AS `id` FROM `b` WHERE (table_c_id = 'a')))


来源:https://stackoverflow.com/questions/5380595/zend-select-not-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!