I have two queries that I am unioning and would like to order them. I would like to order them on the second element, the date. My queries look like this:
$query2
->select ($db->quoteName(array('c.event','b.date','b.type','d.name')))
->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).')');
$query
->select ($db->quoteName(array('b.event','a.date','a.type','b.id')))
->from ($db->quoteName('app_event_animal', 'a'))
->join('INNER', $db->quoteName('app_events', 'b') . 'ON (' .$db->quoteName('a.event'). '=' .$db->quoteName('b.id').')')
->where ($db->quoteName('a.animal') . 'LIKE' . $db->quote($anid))
->union ($query2);
From reading the instructions at [https://docs.joomla.org/Using_the_union_methods_in_database_queries], I think I want to put the query after the union statement. So the last two lines of my second query might look like this:
->union ($query2)
->order($db->quote(date) . ' DESC');
But I don't think I have the syntax right as I keep getting errors like - 1221 - Incorrect usage of UNION and ORDER BY etc.
What would be the correct way to order this union please?