Jump to content

[SOLVED] Return results beginning with first initial


sphinx9999

Recommended Posts

Hi,

 

I need to write a query to return all results beginning with a certain initial character and this character should be alphabetically (or numerically) the first in all results (...not very clear, soz). For example, I have a database with the following rows:

 

banana, bonzai, butter, cat, cough, dog, doughnut

 

I would want the query to return 'banana', 'bonzai', 'butter' ('b' is the first initial in the database).

 

As a starter, so far I have got:

 

SELECT word FROM tablename WHERE...

 

Impressed? ;)

@revraz: thanks for your help, it got me thinking and I then came up with the following:

 

SELECT word FROM tablename WHERE LEFT(LOWER(word),1) = (SELECT LEFT(LOWER(word),1) FROM tablename ORDER BY word LIMIT 1)

 

which works nicely. I'm pretty confident that there must be a more efficient query than this though, so if anyone fancies a go...

 

Ta

You can use WHERE fieldname LIKE b%  if you just want what starts with b, or you can replace b with a variable.

 

The problem is I don't know what the first initial ('b' in this case) is going to be. The subquery

SELECT LEFT(LOWER(word),1) FROM tablename ORDER BY word LIMIT 1

works that out but I could not figure out a way of using a LIKE comparison in the main query:

 

SELECT word FROM tablename WHERE LOWER(word) LIKE (SELECT LEFT(LOWER(word),1) FROM tablename ORDER BY word LIMIT 1)

 

This then doesn't let me use the '%' extender.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.