简体   繁体   English

如果没有匹配项,MySQL返回默认记录(无LIMIT)

[英]MySQL return default record if no matches (without LIMIT)

I have a table like this: 我有一张这样的桌子:

-----------------------------------------
|  ID   |  ACTIVE  |       MESSAGE      |
-----------------------------------------
|   0   |     0    |   Default message  |
-----------------------------------------
|   1   |     1    |   Message one      |
-----------------------------------------
|   2   |     1    |   String two       |
-----------------------------------------
|   3   |     0    |   Text three       |
-----------------------------------------

I have been looking for quite a few hours for a MySQL query showing me the record with ID = 0 as default result if no message is 'active'. 我一直在寻找MySQL查询几个小时,如果没有消息处于“活动”状态,则向我显示ID = 0的记录作为默认结果。 If there are one or more active message(s) I like to get these records. 如果有一条或多条活动消息,我希望获得这些记录。

SELECT * FROM table WHERE ACTIVE = 1;

Also, an option would be to add the default record manually in the query by a UNION or similar idea. 同样,一个选项是通过UNION或类似的想法在查询中手动添加默认记录。 Adding the default record always, ORDER and then LIMIT 1 doesn't work for me, as I need to get back all active messages if existing, not one only. 总是添加默认记录, ORDER ,然后是LIMIT 1这对我来说不起作用,因为我需要找回所有active消息(如果存在的话),而不仅仅是一条消息。

One more constraint: My table and the WHERE condition are more complex in real world, dealing with start and end timestamp comparison. 另一个约束:我的表和WHERE条件在现实世界中更加复杂,用于处理开始和结束时间戳比较。

What about this (untested): 那么(未测试)呢:

SELECT * FROM table WHERE id = 0 AND NOT EXISTS (SELECT * FROM table WHERE active = 1)
UNION SELECT * FROM table WHERE ACTIVE = 1;

That's probably not very efficient, but it depends on the number of records. 这可能不是很有效,但是取决于记录的数量。
An index on active could help, in case. 万一有一个活跃的指数可能会有所帮助。

It should fit your question: if there are active = 1 rows, they're returned from the second query of the union, while the first part resolves to the empty set (as the EXISTS subquery would fail). 它应该适合您的问题:如果有active = 1行,则它们从并集的第二个查询返回,而第一部分解析为空集(因为EXISTS子查询将失败)。 If there are not, the second query returns nothing while the first part returns the row with id = 0 , as the EXISTS subquery now will succeed. 如果没有,则第二个查询将不返回任何内容,而第一部分将返回id = 0的行,因为EXISTS子查询现在将成功。

Save the default message (id = 0) in your actual application code, just query it once and save it. 在您的实际应用程序代码中保存默认消息(id = 0),只需查询一次并保存。 Use the query you've wrote up there, if there are no results, then use the default message that you've saved in your application code. 使用您在此处编写的查询,如果没有结果,则使用保存在应用程序代码中的默认消息。

What you're trying to do isn't very clean, there's ways to do it all within MySQL, as watery's answer demonstrates, but it's not efficient and not the best way to handle your issue. 正如watery的答案所证明的那样,您尝试做的事情不是很干净,有多种方法可以在MySQL中完成所有工作,但这并不是有效的方法,也不是解决问题的最佳方法。

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

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