Mysql PHP,如何选择以特定字符开头的数据

Mysql PHP,如何选择以特定字符开头的数据

问题描述:

I have a table cities:

+----+--------+
| id | zip    | 
+----+--------+
|  1 | 07500  | 
|  2 | 07501  | 
|  3 | 75000  | 
|  4 | 75001  | 
|  5 | 75002  | 
+----+--------+

And I need to select data where the field zip start with 750, so I've tried :

SELECT FROM cities WHERE ZIP LIKE '%750%'

But this returns me all data in the table that contain 750 and this isn't normal. How could I tell my query to select data that start with 750 ?

我有一个表 cities code>: p>

   + ---- + -------- + \ N |  id |  zip |  
 + ---- + -------- + \ N |  1 |  07500 |  
 |  2 |  07501 |  
 |  3 |  75000 |  
 |  4 |  75001 |  
 |  5 |  75002 |  
 + ---- + -------- + 
  code>  pre> 
 
 

我需要选择 field zip code>的数据 从 750 code>开始,所以我尝试过: p>

  SELECT FROM cities WHERE ZIP LIKE'%750%'
  code>   pre> 
 
 

但这会返回包含 750 code>的表中的所有数据,这不正常。 我怎么能告诉我的查询选择以 750 code>开头的数据? p> div>

Do this query:

SELECT FROM cities WHERE ZIP LIKE '750%'

Explanation

% is a special MySQL character that means any character, empty string or group of characters.

Examples:

LIKE '%a%' -- matches: a, ant, track | any string that contains a in any location
LIKE 'a%'  -- matches: a, ant        | strings that start with a
LIKE '%a'  -- matches: a, data       | strings that end with a

This should make the magic:

SELECT FROM cities WHERE ZIP LIKE '750%'

% at begin means any thing before.

LIKE '750%' 

should do the trick

if your string contains '%' character than you would need to use \%