[英]SQL join on values not in table primary keys
我需要獲取未分配給用戶的批次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
);
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 = ?
這是一種經典的查詢類型,可以用兩種方式編寫
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 = ?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.