简体   繁体   中英

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

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.

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

here field1 is your "Countries like US" and field2 is "Countries like ALL" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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