简体   繁体   中英

How to select titles that are like the first n characters of a string?

Here's an example

There are titles of some animes:

|_title_|
|My hero Academia|
|My hero Academia Season 2|
|My hero Academia Season 3|
|My hero Academia Season 4|

And I'd like to select those titles, that contain the first 10 character of the first record, so "My Hero Academia" in this example

It's important that it must be the first N characters, like 10,15,20. So SELECT title FROM tablename WHERE title LIKE "%My hero Academia%" is not the solution I'm looking for.

Also: this is just an example,there are many other titles too, and I don't always know what the first 10 characters are. So I also can't simply put the first 10 characters of "My hero academia" in the WHERE title LIKE clause.

I mean something like this:

SELECT title FROM table_name WHERE title LIKE the first 10 characters of a given string

Is there a way to do that with SQL? Thank you for any help in advance!

for filter a string for a partial fixed value you can use like operator like 'yourstring%' eg:

    SELECT title 
    FROM your_table  
    WHERE title LIKE 'thefirst10%'  

or use a string fuction like substr or left

    SELECT title 
    FROM your_table  
    WHERE left(title,10) = 'thefirst10'  

    SELECT title 
    FROM your_table  
    WHERE substr(title,1,10) = 'thefirst10'  

像这样输入10个字符:

WHERE title LIKE 'aaaaaaaaaa%'
WHERE SUBSTRING(title, 1, n) = 'aaaaaaaaa'

尝试这个:

SELECT title FROM table_name WHERE title like "data structure%"
SELECT title FROM TABLE_NAME WHERE title LIKE '%'  + substring('AAA' , 0 ,2)

substring函数的第一个参数代表您的字符串,第二个开始索引和第三个结束索引。您可以根据需要更改结束索引。

使用通配符(%):

SELECT title FROM table_name WHERE title LIKE "1234567890%"

this could help you it qorks for my postgray11. ithink it will hwlp for your mysql

select * from t1 where title LIKE CONCAT((select * from t1 LIMIT 1),'%');

demo here

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