0

我需要获取未分配给用户的批次 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_id,否则它可以工作。而且我不能只是将另一列添加到批处理中,我试过了,但它需要做很多工作。有一个更好的方法吗?我不关心优化我只需要它工作。

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

2 回答 2

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 = ?
于 2013-11-01T19:07:25.803 回答
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 = ?
于 2013-11-01T19:09:36.667 回答