简体   繁体   中英

SQL Query with LIKE doesn't work unless % is at end

I am new to SQL and learning about LIKE. I installed PostgreSQL and started running commands via psql in the command line. Everything works as expected, except the following query:

SELECT *
FROM movie
WHERE mov_title LIKE '%an Beauty';

which failed to find the movie with mov_title = 'American Beauty'.

However, this one does work:

SELECT *
FROM movie
WHERE mov_title LIKE 'American B%';

Playing around, I realized that the query works if and only if the % is the last character in the string. However, looking at the documentation for LIKE, there is no need for % to be the last character, so I'm stumped. Would greatly appreciate some ideas.

EDIT: I was asked for some data, so here it is:

mov_id  |                     mov_title
--------+----------------------------------------------------
922     | Aliens
905     | Amadeus
914     | American Beauty

There are other columns but they are not relevant to the question. mov_id is the primary key.

EDIT 2: Here is info on the movie database. Apparently mov_id is not the primary key after all. 在此处输入图像描述

My guess is that this movie title has some kind of trailing whitespace or other characters in it. Try the following query:

SELECT *
FROM movie
WHERE mov_title LIKE '%an Beauty%';

If this works, then it means that perhaps something is following Beauty in the movie title.

Edit:

When using LENGTH on a CHAR column in Postgres, trailing whitespace characters are not included in the count. This, along with a handful of other quirks, are reasons why it is generally preferable to use VARCHAR rather than CHAR .

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