SQL: 如何在同一行显示WHERE IN 和WHERE NOT IN?

SQL: How to show the WHERE IN and WHERE NOT IN in the same line?

早安大师们。

基本上我想显示 3 tables。但我有一些条件:

在 运行 上面的代码之后,我遇到了语法错误。它一直工作到现在:

SELECT  `perangkat`.`kd_jp`,  `perangkat`.`no_seri`,  `perangkat`.`status`,  
        `jenis_perangkat`.`nm_jp`,  `jenis_perangkat`.`merk_jp`
FROM`perangkat`
INNER JOIN `jenis_perangkat` 
ON `jenis_perangkat`.`kd_jp` = `perangkat`.`kd_jp` 
WHERE perangkat.kd_jp IN (select sedia.kd_jp from sedia) 

但是当我添加 NOT IN 时它不起作用:and where perangkat.kd_jp not in (select pasang.kd_jp from pasang);

所以这是出现语法错误的查询:

SELECT  `perangkat`.`kd_jp`,  `perangkat`.`no_seri`,  `perangkat`.`status`,  
        `jenis_perangkat`.`nm_jp`,  `jenis_perangkat`.`merk_jp`
FROM`perangkat`
INNER JOIN `jenis_perangkat` 
ON `jenis_perangkat`.`kd_jp` = `perangkat`.`kd_jp` 
WHERE perangkat.kd_jp IN (select sedia.kd_jp from sedia) 
  AND where perangkat.kd_jp not in (select pasang.kd_jp from pasang);

您只能有一个 WHERE 子句。将 WHERE ... AND WHERE ... 更改为 WHERE ... AND ...:

SELECT `perangkat`.`kd_jp`, `perangkat`.`no_seri`, `perangkat`.`status`,
  `jenis_perangkat`.`nm_jp`, `jenis_perangkat`.`merk_jp` 
FROM `perangkat`
INNER JOIN `jenis_perangkat`
  ON `jenis_perangkat`.`kd_jp` = `perangkat`.`kd_jp`
WHERE perangkat.kd_jp IN (SELECT sedia.kd_jp FROM sedia)
  AND perangkat.kd_jp NOT IN (SELECT pasang.kd_jp FROM pasang);

你不能使用 and where:

and where perangkat.kd_jp not in (select pasang.kd_jp from pasang);

只需使用:

and where perangkat.kd_jp not in (select pasang.kd_jp from pasang);

SQL sintaxe select sintaxe 是

select * from [table] WHERE ... AND ... AND ... OR ...

所以

SELECT  `perangkat`.`kd_jp`,  `perangkat`.`no_seri`,  `perangkat`.`status`,  `jenis_perangkat`.`nm_jp`,  `jenis_perangkat`.`merk_jp`FROM`perangkat`INNER JOIN `jenis_perangkat` ON `jenis_perangkat`.`kd_jp` = `perangkat`.`kd_jp` where perangkat.kd_jp in (select sedia.kd_jp from sedia) and perangkat.kd_jp not in (select pasang.kd_jp from pasang);

更新

更好的解决方案是使用 EXISTS 而不是 INNOT IN

SELECT a.kd_jp, a.no_seri, a.status, b.nm_jp, b.merk_jp 
FROM perangkat a 
INNER JOIN jenis_perangkat b  ON b.kd_jp = a.kd_jp 
WHERE EXISTS (SELECT c.kd_jp FROM sedia c WHERE c.kd_jp = a.kd_jp) 
AND NOT EXISTS (SELECT c.kd_jp FROM pasang c WHERE c.kd_jp = a.kd_jp);