主要是考虑改进查询的性能,以及是否能够在单个查询中解决我在下面解释的一个用例:
涉及2个表:
Table 1: EMPLOYEE (column1, column2, email1, email2, column5, column6)
Table 2: EMAILLIST (email)
我的要求是,我想获取/获取表EMPLOYEE中的所有记录,条件是email1或email2在EMAILLIST表中没有匹配的条目。简单地说,如果email1或email2在EMAILLIST表中匹配,则应忽略这些记录。
在这种情况下,EMPLOYEE.EMAIL1,EMPLOYEE.EMAIL2和EMAILLIST.EMAIL将始终存储单个电子邮件地址。
我们正在使用PostgreSQL v8.2.3,如果重要的话。
赞赏任何指针/想法/逻辑。
UPDATE:目前,我们已经以这种方式实现:从EMPLOYEE表获取所有记录并存储在Java对象中以及每个条目(for循环),这反过来检查EMAILLIST表,这在性能方面成本很高。
答案 0 :(得分:1)
为我处理的每个rdbms处理此问题的最有效方法是使用外连接来处理它:
SELECT whatever
FROM employee AS e
LEFT JOIN emaillist AS em1 ON e.email1 = em1.email
LEFT JOIN emaillist AS em2 ON e.email2 = em2.email
WHERE em1.id IS NULL
AND em2.id IS NULL
一般情况下,我认为您会发现,将数据库查询放入循环的任何情况都是非常不理想的。 :)
答案 1 :(得分:1)
有三种方法可以处理这个
SELECT *
FROM employee AS e
LEFT JOIN emaillist AS em
ON e.email1 = em.email
or e.Email2 = em.email
WHERE
em.email is null
SELECT *
FROM employee AS e
WHERE
NOT EXISTS (SELECT *
FROM
emaillist AS em
WHERE e.email1 = em.email
or e.email2 = em.Email)
SELECT *
FROM employee AS e
WHERE
e.email1 NOT IN (SELECT email
FROM
emaillist)
and
e.email2 NOT IN (SELECT email
FROM
emaillist)