Postgresql

如何在同一個查詢和表中使用“WHERE”和“WHERE NOT EXISTS”?

  • July 13, 2018

我正在嘗試在同一個查詢中添加WHERE兩者WHERE NOT EXISTS。下面提到的 query1 工作正常,但它返回所有不屬於 company1 的 t1 數據。所以我嘗試了query2,但沒有運氣。我怎樣才能得到想要的結果?

select * from t1 where not exists
(select * from t2 inner join t3 on(t3._id = t2.department_id)where t2.category_id = t1._id AND t3._id = 27 AND t3.company_id = 1) 
ORDER BY "ctsName"
select * from t1 where company_id = 1 AND where not exists
(select * from t2 inner join t3 on(t3._id = t2.department_id)where t2.category_id = t1._id AND t3._id = 27 AND t3.company_id = 1) 
ORDER BY "ctsName"

WHERE是分隔符,而不是操作,後面的位WHERE描述了您希望在結果中看到的行。

要應用兩個條件,請使用ANDOR組合它們。

select * from t1 
where not exists (select * from t2 inner join t3 on(t3._id = t2.department_id)
 AND  t2.category_id = t1._id AND t3._id = 27 AND t3.company_id = 1) 
ORDER BY "ctsName"

引用自:https://dba.stackexchange.com/questions/211733