开发者

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

开发者 https://www.devze.com 2023-01-20 05:15 出处:网络
I am using a query like this: SELECT * FROM table1 WHERE countries LIKE \'%US%\' OR countries LIKE \'%ALL%\';

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

开发者_JAVA百科

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)


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消