views:

35

answers:

5

I have a situation where I've got file names stored in two fields in a table. The fields are called file1 an file2.

file1 is ALWAYS present. file2 might not be present for some rows.

I want to write a query that would get me only a certain extension of files from the DB.

For that I am using for example

...WHERE file1 LIKE '%jpg%'

But here I cannot use AND file2 LIKE '%jpg%' because file2 may be empty, which is ok.

So what do I do so that the LIKE condition is only applied when the field is not empty?

A: 

Could use just use OR file2 LIKE '%jpg%'?

Jeremy DeGroot
No. That would get him File1 even if it had the wrong extenstion.
AllenG
BOTH the files should have the same extension. Using OR would return rows where the extension is not jpg in one file name.
psyb0rg
+2  A: 

Make use of parenthesis to clarify.

WHERE file1 LIKE '%jpg%' AND (file2 LIKE '%jpg%' OR file2 is NULL OR file2 = '')

or whatever other conditions you need from file2

sleepynate
+2  A: 

Try this:

AND (file2 LIKE '%jpg%' OR file2 IS NULL (or file2 = '' depending on what your empty value is) )
Noah Goodrich
+2  A: 

Try AND (file2 is NULL or file2 LIKE %jpg%)

AllenG
@Allen: It looks like you're missing quotes around `%jpg%` :)
Daniel Vassallo
+2  A: 
SELECT  * 
FROM    files 
WHERE   file1 LIKE '%jpg' AND 
        (file2 LIKE '%jpg' OR file2 IS NULL);

Test case:

CREATE TABLE files (file1 varchar(20), file2 varchar(20));

INSERT INTO files VALUES ('pic1.jpg', NULL);
INSERT INTO files VALUES ('pic2.png', NULL);
INSERT INTO files VALUES ('pic3.jpg', 'otherpic.jpg');
INSERT INTO files VALUES ('pic4.png', 'nopic.jpg');
INSERT INTO files VALUES ('pic5.bmp', 'otherpic.gif');

Returns:

+----------+--------------+
| file1    | file2        |
+----------+--------------+
| pic1.jpg | NULL         |
| pic3.jpg | otherpic.jpg |
+----------+--------------+
2 rows in set (0.00 sec)
Daniel Vassallo