I am having trouble using the union functions in Joomla. This is the SQL I need:
SELECT
*
FROM
(SELECT
o.title AS org_name,
u1.name AS username,
'president' AS `type`
FROM
org o
LEFT JOIN users u1
ON u1.`id` = o.`president`
UNION
ALL
SELECT
o.title AS org_name,
u1.name AS username,
'secretary' AS `type`
FROM
org o
LEFT JOIN users u1
ON u1.`id` = o.`secretary`
UNION
ALL
SELECT
o.title AS org_name,
u1.name AS username,
'treasurer' AS `type`
FROM
org o
LEFT JOIN users u1
ON u1.`id` = o.`treasurer`) AS a
ORDER BY a.org_name ;
This is my Joomla code:
$q2 = $db->getQuery(true);
$q1 = $db->getQuery(true);
$query = $db->getQuery(true);
$q2
->select('o.title AS show_name, u1.name AS name,' . $db->quoteName('president') . 'as' . $db->quoteName('type'))
->from($db->quoteName('#__agshows_shows', 'o'))
->join('LEFT', $db->quoteName('#__users', 'u1') . ' ON (' . $db->quoteName('u1.id') . ' = ' . $db->quoteName('o.president') . ')')
;
$q1
->select('o.title AS show_name, u1.name AS name')
->from($db->quoteName('#__agshows_shows', 'o'))
->join('LEFT', $db->quoteName('#__users', 'u1') . ' ON (' . $db->quoteName('u1.id') . ' = ' . $db->quoteName('o.secretary') . ')')
;
$query
->select('*')
->from($db->quoteName('#__agshows_shows', 'a'))
->union($q1)
->union($q2)
->order($db->quoteName('a.title') . ' ASC')
;
$mailshot = $db->setQuery($query)->loadObjectList();
I keep getting this SQL Error:
1221 Incorrect usage of UNION and ORDER BY SQL=SELECT * FROM
ruq1h_agshows_shows
ASa
ORDER BYa
.title
ASC UNION ( SELECT o.title AS show_name, u1.name AS name FROMruq1h_agshows_shows
ASo
LEFT JOINruq1h_users
ASu1
ON (u1
.id
=o
.secretary
)) UNION ( SELECT o.title AS show_name, u1.name AS name,president
astype
FROMruq1h_agshows_shows
ASo
LEFT JOINruq1h_users
ASu1
ON (u1
.id
=o
.president
))
What am I doing wrong?