简体   繁体   中英

SQL - How to avoid multiple OR operators in WHERE clause?

sqlite> .schema movie
CREATE TABLE movie (
  id INTEGER PRIMARY KEY, title TEXT, year INTEGER, nth TEXT, for_video BOOLEAN
  );
sqlite>
sqlite>
sqlite>

For the question:

Which movie(s), not counting movies whose titles start with punctuation, come first in alphabetical order, and which come last?

below syntax:

SELECT title 
FROM movie 
WHERE NOT(title LIKE '%!%' or title LIKE '%#%' or title LIKE '%$%')  
ORDER BY title ASC LIMIT 1;

has never ending or operators.


Syntax should work in mysql and sqlite

How to avoid multiple OR operators that check for punctuations? yet to add more OR operators for punctuation check...

For th first part (multiple ORs). Also note that the syntax is different for the join ( Like )

You can create a table for punctuations and add the data into it

 Create table Punctuations (punckSign varchar(10))

 insert into Punctuations
 values ('!'), ('#'), ('$')

Then left join that with movie table as follows

MySQL

 SELECT title FROM movie m
 Left join Punctuations p 
 on  title  like concat('%',p.punckSign,'%')  
 where p.punckSign is null

SQLite

 SELECT title FROM movie m
 Left join Punctuations p 
 on  title  like '%'|| p.punckSign || '%'  
 where p.punckSign is null

Try the below using REGEXP

SELECT title 
FROM movie 
WHERE title not REGEXP '!|#|$'
ORDER BY title ASC LIMIT 1;

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