简体   繁体   English

如何编辑此 mySQL 查询以在满足条件或未找到行时返回结果?

[英]How to edit this mySQL query to return result when a condition is met or a row is not found?

I have the data table and it is like this:我有data表,它是这样的:

id ---- user ---- status
1 ----- abc ----- idle
2 ----- def ----- received

that I use the following to get the result我使用以下内容来获得结果

WHERE status ='idle' AND user='abc'

The above is my try to return the result of the query if status = idle' for abc`以上是我尝试返回查询结果 if status = idle' for abc`

However, what I really is to get the result for abc even if it does not exist in the data table and I tried this但是,即使data表中不存在abc的结果,我真正要得到的结果我也试过了

 WHERE (status ='idle' or not exists(select * from data where user='2NnG1zvogogH' limit 1)  ) AND user='abc'

without luck.没有运气。

Is this possible?这可能吗?

I think what you want is:我想你想要的是:

WHERE (status = 'idle' and user = 'abc')
OR NOT EXISTS (SELECT * FROM data WHERE user = 'abc')

There's no need for LIMIT 1 when a subquery is used with EXISTS , the database knows that it only has to match a single row.当子查询与EXISTS使用时,不需要LIMIT 1 ,数据库知道它只需要匹配一行。

SELECT * FROM (    
    SELECT id, user, status FROM data WHERE status = 'idle'
    UNION
    SELECT * FROM (
        SELECT 0 id, IF((SELECT COUNT(id) FROM data WHERE user = 'abc') = 0, 'abc', NULL) user, 'status' status
    ) tmp
    WHERE user= 'abc'
) tmp2 ORDER BY id

SELECT id, user, status FROM data WHERE status = 'idle' will return all the results in the table that meet this criteria. SELECT id, user, status FROM data WHERE status = 'idle'将返回表中满足此条件的所有结果。 That one is obvious enough.这一点已经很明显了。

SELECT 0 id, IF((SELECT COUNT(id) FROM data WHERE user = 'abc') = 0, 'abc', NULL) user, 'status' status will always return one line. SELECT 0 id, IF((SELECT COUNT(id) FROM data WHERE user = 'abc') = 0, 'abc', NULL) user, 'status' status总是返回一行。 The only difference will be if user = 'abc' or if user = NULL .唯一的区别是user = 'abc'user = NULL user will return 'abc' if there is no user = 'abc' in the database.如果数据库中没有user = 'abc'user将返回'abc'

SELECT * FROM (...) tmp WHERE user= 'abc' just filters the results from the above query so that if the row is user = NULL then it is not included in the rest of the results. SELECT * FROM (...) tmp WHERE user= 'abc'只是过滤上述查询的结果,如果该行是user = NULL那么它不会包含在其余的结果中。

All of this is then ordered in the outermost query.然后所有这些都在最外面的查询中排序。

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

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