0

目标:返回给定类型的所有记录,其中不存在相反类型。

问题:当我将 Select Count 用作“AND”时,不返回任何记录

SELECT ct.cntrct_id, ar.addr_1, ar.city_nm, ar.st_cd, ar.zip_code, p.phone_nbr, p.frst_nm, p.lst_nm
    FROM addru ad, addrs ar, cntrt ct, persn p, custm cm
    WHERE ad.cntrct_seq = ct.cntrct_seq
    AND ar.addr_seq = ad.addr_seq
    AND p.person_seq = cm.person_seq
    AND cm.clnt_seq = ct.clnt_seq
    AND ad.active_flg = '1'
    AND ad.dist_id = $dist
    AND substring(ct.cntrct_id from 2 for 1) = '$type'
    AND ((SELECT COUNT(*)
            FROM addru ad, addrs ar, cntrt ct, persn p, custm cm
            WHERE ad.cntrct_seq = ct.cntrct_seq
            AND ar.addr_seq = ad.addr_seq
            AND p.person_seq = cm.person_seq
            AND cm.clnt_seq = ct.clnt_seq
            AND ad.active_flg = '1'
            AND ad.dist_id = $dist
            AND substring(ct.cntrct_id from 2 for 1) != '$type') = 0)
    ORDER BY ct.cntrct_id"

复制表定义会占用大量空间,因此如果您需要查看它们,请告诉我哪些(不想因为太多信息而陷入困境)我认为我的错误是合乎逻辑的来自对如何形成sql查询的误解。

4

1 回答 1

1

除非我错过了什么,你为什么不能做

SELECT ...
FROM ...
WHERE ...
GROUP BY ...
ORDER BY ...
HAVING COUNT(*) = 0

这应该比运行两次查询更好,这样您就可以在行级别进行“内联”计数过滤。

于 2013-01-17T14:33:09.633 回答