Question

I want to get certain records that meet certain criteria. One of them is that they can only be found if the current day of the week is found in a certain column. I have the query below, and it works if I just input the weekdays myself, but doesn't return any results if i use a fieldname..

So the field 'dagen' contains either * for any day, of a list of weekdays like '5','6' for Thursday and Friday.

SELECT * FROM playlist_item 
WHERE playlist_id='31' 
AND type_id='56' 
AND jobcomplete='0' 
AND startuur<=TIME(NOW()) AND einduur >=TIME(NOW()) 
AND (dagen='*' OR DAYOFWEEK(NOW()) IN (dagen));

If I replace dagen at the end with .. IN (5,6) it works perfectly, but not when using a column name.. I've tried it without single quotes as a value, with quotes.. None of them work.. What is the correct way to get the result I want?

SQLFiddle exaple can be found here

Was it helpful?

Solution

Assuming that dagen is a column that contains a comma separated list of days of the week, try something like this:-

SELECT * FROM playlist_item 
WHERE playlist_id='31' 
AND type_id='56' 
AND jobcomplete='0' 
AND startuur<=TIME(NOW()) AND einduur >=TIME(NOW()) 
AND (dagen='*' OR FIND_IN_SET(DAYOFWEEK(NOW()), dagen));

Note that a comma separated list is generally a sign of a poorly normalised database.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top