I want to create a complex WHERE query that checks:
If (condition1 = TRUE) AND (condition2 = TRUE) AND (condition3 = TRUE OR condition4 = TRUE)
So the first two conditions MUST always be true and then either condition 3 or 4 MUST be true.
I am trying with the code:
->select ($db->quoteName(array('c.event','b.date','b.type','a.mob','a.joined','a.left')))
->from ($db->quoteName('app_mob_animal', 'a'))
->join('INNER', $db->quoteName('app_event_animal', 'b') . 'ON (' .$db->quoteName('a.mob'). '=' .$db->quoteName('b.mob').')')
->join('INNER', $db->quoteName('app_events', 'c') . 'ON (' .$db->quoteName('b.event'). '=' .$db->quoteName('c.id').')')
->join('INNER', $db->quoteName('app_mob', 'd') . 'ON (' .$db->quoteName('a.mob'). '=' .$db->quoteName('d.id').')')
->where (($db->quoteName('a.animal') . 'LIKE' . $db->quote($anid)), 'AND')
->where (($db->quoteName('a.joined') . '<=' . $db->quoteName('b.date')), 'AND')
->where (($db->quoteName('a.left') . '>=' . $db->quoteName('b.date') .'OR'. ($db->quoteName('a.left') .'LIKE'. $db->quote($emptyDate))));
But when I spit out my responses I am getting results that clearly break the second condition. Here's an except of my results, the second one does not fulfill the criteria.
[0]=>
object(stdClass)#891 (6) {
["event"]=>
string(7) "weighed"
["date"]=>
string(19) "2015-04-19 00:00:00"
["type"]=>
string(3) "mob"
["mob"]=>
string(2) "11"
["joined"]=>
string(19) "2015-04-18 11:39:14"
["left"]=>
string(19) "0000-00-00 00:00:00"
}
[1]=>
object(stdClass)#888 (6) {
["event"]=>
string(9) "vet visit"
["date"]=>
string(19) "2015-03-31 11:46:08"
["type"]=>
string(3) "mob"
["mob"]=>
string(2) "11"
["joined"]=>
string(19) "2015-04-18 11:39:14"
["left"]=>
string(19) "0000-00-00 00:00:00"
}
What is the correct syntax for the WHERE part of this query?
LIKE
operator properly. If your logic is to make an exact match, then use the=
comparison operator. If your logic is to make a partial match, then useLIKE
with a string that includes_
or%
. See the Joomla Documentation recommended syntax here. This is an important whistle to blow to prevent unknowing copy/pasters from using suboptimal coding practices.