有两个表:
[code="sql"]create table a(
id VARCHAR(255) PRIMARY KEY,
name CHAR(50)
);
create table b(
id VARCHAR(255) referrence foreign key a(id),
name CHAR(50)
)[/code]
问:如何查询出表a中id列的值在表b中不存在的记录.
目前我能想到的方法是:
[code="sql"]SELECT
*
FROM
(
SELECT
a.*,
b.id _id
FROM
a
LEFT JOIN b
WHERE
a.id = b.id
)
t
WHERE
t._id IS NULL;[/code]
有没有人能想到更好一点的方法? 请指教! 另外,我用的数据库是DB2.
[code="java"]
select *
from a A
where not exists ( select 1
from b B
where A.id = B.id);
[/code]
效率应该比你的高
你欺负人吧。还能简单?都用了左连了。
select *
from a A
where a.id not in( select b.id from b B )
DB2差集运算:EXCEPT、EXCEPT ALL
-- 求差集:A减B
SELECT * FROM A -- 集合A
EXCEPT
SELECT * FROM B;-- 集合B