Warrior Forum - The #1 Digital Marketing Forum & Marketplace

Warrior Forum - The #1 Digital Marketing Forum & Marketplace (https://www.warriorforum.com/)
-   Programming (https://www.warriorforum.com/programming/)
-   -   Help with simple MySQL Query (https://www.warriorforum.com/programming/755079-help-simple-mysql-query.html)

Bruce Wedding 17th February 2013 01:17 PM

Help with simple MySQL Query
 
I have very little SQL experience and have a problem with a query that seems relatively easy. It's returning a null set and SQL Explain says it's an impossible where.

Here's the query:
SELECT 'password' FROM `album` WHERE `uid`=124 AND instr('title', '21.01')

Here's the DB structure:
http://i49.tinypic.com/11wacdk.jpg

Here's the actual record with the matching uid and title:
http://i49.tinypic.com/2cxgpd5.jpg

Dan Grossman 17th February 2013 02:16 PM

Re: Help with simple MySQL Query
 
INSTR('title', '21.01') looks for the string '21.01' in the string 'title'. That substring does not appear, so the query can never match any rows so none are even checked.

What you meant to write was INSTR(title, '21.01') which looks for the string '21.01' in the column named title.

I've never seen someone use INSTR though. Most people would write
Code:

WHERE uid = 124 AND title LIKE '%21.01%'

Bruce Wedding 17th February 2013 04:01 PM

Re: Help with simple MySQL Query
 
That works, Dan. Thanks a lot.

FirstSocialApps 17th February 2013 07:11 PM

Re: Help with simple MySQL Query
 
Quote:

Originally Posted by Dan Grossman (Post 7751098)
I've never seen someone use INSTR though. Most people would write [code]WHERE uid = 124 AND title LIKE '%21.01%'

Wildcards are the way I have always done a search like this as well. Is there some advantage to using INSTR?

KirkMcD 19th February 2013 06:24 AM

Re: Help with simple MySQL Query
 
For that query, no. In fact it is wrong.
instr returns the position of the substring in the main string.

Dan Grossman 19th February 2013 11:03 AM

Re: Help with simple MySQL Query
 
Quote:

Originally Posted by KirkMcD (Post 7758103)
For that query, no. In fact it is wrong.
instr returns the position of the substring in the main string.

It's not in fact wrong at all. MySQL needs a boolean to evaluate the WHERE clause of the query, and coercing the integer return value of INSTR will have the desired result. INSTR returns 0 if the substring doesn't appear, which is coerced to boolean false. If the substring does appear, its index would be a positive integer, and any positive integer is coerced to boolean true.


All times are GMT -6. The time now is 05:02 AM.