简体   繁体   English

SQL 检查是否存在条件

[英]SQL to check if exists with condition or not exists

I have the following scenario:我有以下情况:

I want to select a mission from a table(missions) for a user (userID=?) , or I will select all missions if user is not assigned to any mission.我想select a mission from a table(missions) for a user (userID=?) ,或者如果用户未分配给任何任务,我将 select 所有任务。

This can be achieved in 2 queries:这可以通过 2 个查询来实现:

   Select * from missions where userID = :ID

If (result is empty)如果(结果为空)

   Select * from missions 

I want these 2 SQL in one SQL if possible any Idea如果可能的话,我想要这些 2 SQL 在一个 SQL 中

I other words.我换句话。 User can eather select messions he assigned to by admin or he can work with all messions.用户可以使用管理员分配的 select 邮件,也可以处理所有邮件。

You may try:你可以试试:

SELECT *
FROM missions
WHERE
    userID = :ID OR
    NOT EXISTS (SELECT 1 FROM missions WHERE userID = :ID);

Should one or more records exist with userID =:ID , the first condition would be true for those records, and the exists condition would also be false, and therefore ignored.如果userID =:ID存在一个或多个记录,则这些记录的第一个条件将为真,并且存在条件也将为假,因此被忽略。 Should no records exist with userID =:ID , then the first condition would always be false, and therefore ignored, while the second condition would always be true, thereby returning the entire table.如果userID =:ID不存在任何记录,则第一个条件将始终为假,因此被忽略,而第二个条件将始终为真,从而返回整个表。

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

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