Search code examples
mysqljoinsql-like

How to use NOT LIKE and JOIN together in mysql?


I need to exclude from query some records, where day name isset in exclude value 'excl_days'.

Simple function is working:

SELECT post_id, start, end, excl_days FROM `mytable_events` 
WHERE `excl_days` NOT LIKE '%".$today_name."%' 
ORDER BY DATE(start) DESC

But with JOIN and GROUP i have empty result after adding NOT LIKE. Without NOT LIKE all is working fine.

SELECT o1.post_id, o1.start, o1.end, o1.excl_days 
FROM `mytable_events` o1 
JOIN `mytable_posts` o2 ON o1.post_id = o2.ID 
WHERE `o1.excl_days` NOT LIKE '%".$today_name."%'
GROUP BY o1.post_id ORDER BY DATE(o1.start) DESC

Full query is:

SELECT o1.post_id, o1.start, o1.end, o1.excl_days 
FROM `mytable_events` o1 
JOIN `mytable_posts` o2 ON o1.post_id = o2.ID 
WHERE DATE(o1.start) <= '".$today."' AND DATE(o1.end) >= '".$today."'
AND o2.post_type = 'events' AND o2.post_status = 'publish' 
AND `o1.excl_days` NOT LIKE '%".$today_name."%'
GROUP BY o1.post_id ORDER BY DATE(o1.start) DESC

How make this to work? Thank you for help.


Solution

  • Try this:

      SELECT o1.post_id, o1.start, o1.end, o1.excl_days 
      FROM `mytable_events` o1 
      JOIN `mytable_posts` o2 ON (o1.post_id = o2.ID 
      AND o1.excl_days NOT LIKE '%".$today_name."%')
      GROUP BY o1.post_id ORDER BY DATE(o1.start) DESC