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
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

Link to comment
Share on other sites

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)?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.