简体   繁体   English

如果第一个为true,如何在MySQL查询中使用OR并忽略第二个条件?

[英]How to use OR in MySQL query and ignore second condition if first is true?

I am using a query like this: 我正在使用这样的查询:

SELECT * FROM table1 WHERE countries LIKE '%US%' OR countries LIKE '%ALL%';

This returns all the entries that have "US" or "ALL" in countries column, but I want it to return ONLY those rows that contains "US", and if non is found then use the next condition and return all that contains "ALL". 这将返回在国家列中具有“ US”或“ ALL”的所有条目,但我希望它仅返回包含“ US”的那些行,如果未找到,则使用下一个条件并返回包含“ ALL”的所有条目”。

Is it possible to do this in only one query? 只能在一个查询中执行此操作吗?

By using a sub-query: 通过使用子查询:

SELECT * 
FROM table1 
WHERE countries LIKE (CASE WHEN (SELECT COUNT(*) 
                                 FROM table1 
                                 WHERE countries LIKE '%US%') = 0
                           THEN '%ALL%'
                           ELSE '%US%'
                       END)

我认为不可能仅使用一个SQL查询。

if you are using mysql, Though i have't try this, you can try this. 如果您使用的是mysql,虽然我还没有尝试过,但是您可以尝试一下。

 SELECT IF(field1 is null, field2, field1) FROM table1;

here field1 is your "Countries like US" and field2 is "Countries like ALL" . 在这里,field1是您的“像美国一样的国家”,field2是“像所有国家一样的国家”。

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

相关问题 如何在第二个查询中使用第一个查询的结果? - How do I use results of first query in second query? 如果条件为真,则在MySQL存储过程中运行查询 - Run a query in a MySQL stored procedure if a condition is true Laravel中的MySQL子查询,如何联接查询并将第二查询的结果作为新列添加到第一查询? - MySQL sub query in Laravel, how to join queries and add second query's result as a new column to first query? 在mysql查询中if为true时,仅使用AND statment - Only use AND statment when if is true in mysql query MySQL如何限制仅从第一个表而不从第二个表的JOIN-Query行数? - MySQL How to limit amount of rows from JOIN-Query only from first Table and not the Second Table? 如何在条件上使用mysql join? - How to use mysql join on or condition? 如果特定条件为真,如何在MySQL中获取特定列的名称? - How to get a specific column's name in mySQL if a specific condition is true? SQL 日期查询 - 此条件成立多长时间 - SQL Dates Query - how long has this condition been true 如何在第一个查询中选择行但在第二个查询中不显示行? - how to select rows in first query but but not present in second query? 如何根据第一个查询结果执行第二个查询 - How to execute second query based on first query result
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM