Jump to content

Conditional Query of some sort


ignace

Recommended Posts

Hi, I have 2 tables:

 

panden

id, pandenid, ..

 

fotos

id, pandenid, hoofdfoto, volgorde

 

I now want to construct a query that takes the picture that has hoofdfoto=1 or when it has no such value for that field it should take the highest number stored in volgorde. I tried

 

SELECT pd.id,ft.filename,max(volgorde)

FROM panden AS pd

LEFT JOIN fotos AS ft ON pd.pandenid=ft.pandenid

GROUP BY pd.pandenid

 

Without any luck. I am not even sure this is possible as the system is MySQL v4.0 which can't be upgraded because the application that uses it is very unstable and they have no idea what kind of implications it may have, another reason is the number of users that use the system daily.

 

Regards,

Ignace

 

 

Link to comment
https://forums.phpfreaks.com/topic/209251-conditional-query-of-some-sort/
Share on other sites

The last query I tried was:

 

SELECT pd.pandid,ft.filename,max(ft.volgorde) AS volgorde
FROM panden AS pd
LEFT JOIN fotos AS ft ON pd.pandid=ft.pandenid
WHERE ft.filename IS NOT NULL
GROUP BY pd.pandid
ORDER BY pd.pandid,if(ft.hoofdfoto=1,ft.hoofdfoto,volgorde) DESC

 

Except it ignores ft.hoofdfoto entirely while it should favor ft.hoofdfoto if it's value equals 1

 

@fenway damn I really would have wanted to do this in one query, thanks

But, the problem is hoofdfoto (main picture) will not always be 1 so if i write:

 

SELECT pd.pandenid,ft.filename,max(ft.volgorde) AS volgorde
FROM panden AS pd
LEFT JOIN fotos AS ft ON pd.pandenid=ft.pandenid AND ft.hoofdfoto=1
WHERE ft.filename IS NOT NULL
GROUP BY pd.pandid
ORDER BY pd.pandid,if(ft.hoofdfoto=1,ft.hoofdfoto,volgorde) DESC

 

I only get the records which have ft.hoofdfoto=1 while it should take the highest value for volgorde if hoofdfoto=0 so something like ON pd.pandenid=ft.pandenid AND (ft.hoofdfoto=1 XOR ?). But I have no clue as to how I could achieve this. Maybe ft.volgorde=volgorde (with an OR instead of XOR)?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.