3

The following sql statement:

SELECT 
    profile_pic
FROM
    (`member`) 
WHERE 
    `active` = 1

produces the following result:

profile_pic
    1_1345694557.jpg
    <blank_value>
    <blank_value>
    <blank_value>

I want the "blank values" to default to "no_prof_thumb.jpg".

So I created this statement:

SELECT 
    REPLACE(IF (CHAR_LENGTH(profile_pic) > 0, profile_pic, 'no_prof.jpg' ), '.jpg', '_thumb.jpg') AS profile_pic 
FROM 
    (`member`) 
WHERE 
    `active` = 1

Here is the result:

profile_pic
1_1345694557_thumb.jpg
no_prof_thumb.jpg
no_prof_thumb_thumb.jpg
no_prof_thumb_thumb_thumb.jpg

Why does _thumb keep appending itself to the value in the previous row?

How should I fix my expression?


Update

This issue occurs on a GoDaddy mySQL database. I reproduce when it connecting remotely through SQLyog and when I log into GoDaddy and run it through phpMyAdmin.

However, I cannot reproduce locally nor on sqlFiddle.
So it must be some kind of configuration issue.

2 Answers 2

3

You needed to use IF outside the REPLACE statement like this.

SELECT 
    IF (profile_pic = '', 'no_prof.jpg', 
        REPLACE(profile_pic, '.jpg', '_thumb.jpg')) AS profile_pic 
FROM 
    (`member`) 
WHERE 
    `active` = 1

You can also use CASE statement instead of IF like this:

SELECT
  CASE  profile_pic
    WHEN '' THEN 'no_prof.jpg'
    ELSE REPLACE(profile_pic, '.jpg', '_thumb.jpg')
  END AS profile_pic
FROM member
WHERE active = 1;

See this fiddle

1
  • 1
    I reproduced this issue on a GoDaddy mysql database. I tested the sql on sqlfiddle and locally and could not reproduce. So, it must be some kind of configuration issue on their servers. Your suggestion works though. Ty.
    – ray
    Aug 25, 2012 at 13:33
1

The nested logic is a little weird. You can simplify it with a CASE statement. If the value is an empty string, just return no_prof_thumb.jpg. Otherwise, replace .jpg with _thumb.jpg.

SELECT
  CASE  
    WHEN profile_pic = '' THEN 'no_prof_thumb.jpg'
    ELSE REPLACE(profile_pic, '.jpg', '_thumb.jpg')
  END AS profile_pic
FROM member
WHERE active = 1

I can't, explain why you're getting the weird result you're getting without further testing though.

1
  • small syntax issue: closing parenthesis on REPLACE. Otherwise, it works.
    – ray
    Aug 25, 2012 at 13:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.