SQL连接不在表主键中的值

时间:2013-11-01 19:03:58

标签: sql join

我需要获取未分配给用户的批处理ID。我有这个选择声明:

SELECT batch.id 
FROM batch 
WHERE (SELECT batch.id 
       FROM batch 
       JOIN user 
       WHERE batch.id = user.batch_id) "+ "!= batch.id 
  AND submitted = 0 
  AND batch.project_id = ?

除非没有为用户分配batch_ids,否则它有效。我不能只是批量添加另一列,我试过但它需要很多工作。有一个更好的方法吗?我不关心优化我只是需要它才能工作。

CREATE TABLE batch
(
    id integer not null primary key autoincrement,
    filepath varchar(255) not null,
    project_id integer not null,
    submitted boolean not null
);

CREATE TABLE user
(
    id integer not null primary key autoincrement,
    first_name varchar(255) not null,
    last_name varchar(255) not null,
    user_name varchar(255) not null,
    password varchar(255) not null,
    num_records integer not null,
    email varchar(255) not null,
    batch_id integer not null
);

2 个答案:

答案 0 :(得分:0)

SELECT b.id
FROM batch b
LEFT JOIN user u ON u.batch_id = b.id
WHERE u.id IS NULL
  AND b.submitted = 0
  AND b.project_id = ?

答案 1 :(得分:0)

这是一种经典的查询类型,可以用两种方式编写

select batch.id
from batch
left join user on user.batch_id = batch.id
where user.id is null
and batch.submitted = 0 
and batch.project_id = ?

select batch.id
from batch
where not exists (select 1 from user
where user.batch_id = batch.id)
and batch.submitted = 0 
and batch.project_id = ?