views:

41

answers:

3

i want to get distinct values for a field, let say: field1... ok this needs a query like: "select distint(field1) from table"

however for some records, field1 is empty and there is another column that is an alternative to field1, which is field2. now; for the records where field1 is empty i need to use the value of field2. i think i need sort of a conditional select statement with if control something like:

"select distinct( (if(field1!='') field1 else field2) ) from table"

but i have no idea on how to write it. any help is appricated...

+1  A: 

SELECT DISTINCT IFNULL(field1,field2) FROM table

should do the trick.

Peter Tillemans
your solution returned 64 results while my query below returned 74!?! i m analyzing the results to see the differences and will post my comments later here.
emre
A: 

i think i did it (not sure if the result is correct):

SELECT DISTINCT (
 IF( field1 <> '', field1, field2)
)
FROM table
emre
The NULL value and the empty string are not the same. Maybe that explains the difference?
Peter Tillemans
A: 
SELECT DISTINCT (
 IF( coalesce(field1,'') <> '', field1, field2)
)
FROM table

This would work for both null and empty field1.

ceteras
thanks! it works.
emre