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

时间:2022-03-10 15:39:51

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".

这将返回在countries列中具有“US”或“ALL”的所有条目,但我希望它仅返回包含“US”的行,如果找到non,则使用下一个条件并返回包含“ALL”的所有内容”。

Is it possible to do this in only one query?

是否可以只在一个查询中执行此操作?

3 个解决方案

#1


2  

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)

#2


0  

I don't think it's possible in just one SQL query.

我认为只有一个SQL查询是可能的。

#3


0  

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是“像ALL一样的国家”。

#1


2  

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)

#2


0  

I don't think it's possible in just one SQL query.

我认为只有一个SQL查询是可能的。

#3


0  

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是“像ALL一样的国家”。