简体   繁体   English

对表主键中没有的值进行SQL连接

[英]SQL join on values not in table primary keys

I need to get the batch ids that are not assigned to a user. 我需要获取未分配给用户的批次ID。 I had this select statement: 我有以下选择语句:

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 = ?

It worked except when no batch_ids are assigned to users. 除未将batch_id分配给用户外,其他方法均有效。 And I can't just add another column to batch to, I tried but it requires way to much work. 我试过不只是将另一列添加到批处理中,但这需要很多工作。 Is there a better way to do this? 有一个更好的方法吗? I don't care about optimization I just need it to work. 我不在乎优化,我只需要工作即可。

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
);
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 = ?

This is a classic type of query which can be written in two ways 这是一种经典的查询类型,可以用两种方式编写

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 = ?

or 要么

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 = ?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM