PDA

View Full Version : Problem with SQL query.


Steven_Smith
05-26-2003, 07:29 PM
Hey I am having a problem forming an SQL statement.

Ok, the field I want to search has many words in it.

example

name:
Steve Smith
Elvis Presley
Marlyn Manson

and I want to show all the 'Smiths' in the field.

What would the sql be.

select 'smith' FROM name WHERE name='smith'
-or- select 'smith' FROM name LIKE name='smith'

I am not sure how to search when there is more than two words.

Thanks
Steve

raf
05-26-2003, 07:49 PM
It should be something like

sql="SELECT the variabels you need FROM tablename WHERE name LIKE '%smith%'"

more info on
http://www.mysql.com/doc/en/String_comparison_functions.htmlµ

Note: 'Tom Smitherly' would also be selected ! But by using other wildcards or regexs, you can narrow it down.

Steven_Smith
05-26-2003, 07:58 PM
Thanks. So the deal is to put % % around the query string.

Great! :thumbsup:

raf
05-26-2003, 08:22 PM
the deal is:
- operator '=' --> if the value of the field needs to be exactly the value (for example: name='smith'. will only return records where the value for name is 'smith')
- operator 'LIKE' --> the value of the field can be a value + some other characters. These other characters can be represented with wildcards like %. % means that it doesn't matter what comes before or after the value (for example: name LIKE '%smith%' wil return the records with 'blacksmith', 'i am no smith !', 'dedzesmithxqsfdq' as values in the name column)
- wildcards can only be used with the LIKE operator
- you can have other wildcards or use regex etc to specify the 'correct' values

Steven_Smith
05-26-2003, 08:29 PM
My Favorite Quote, from the back of the 'Mastering Regular Expressions' from O'reilley books.

'Written in the lucid, entertaining tone that makes a complex, dry topic crystal-clear to thousands of programmers...'

Thanks for the help RAF. SQL makes more sense to me now.

Steve

raf
05-26-2003, 08:43 PM
You're welcome.
LOL. I'd need to read that book.

Spookster
05-27-2003, 05:11 PM
If you need help with learning SQL there is an excellent interactive learning site here:

Beginners Course
http://www.sqlcourse.com/

Advanced Course
http://sqlcourse2.com/

They allow you to work with a live database with short exercises to practice what you learn.