I have a fairly complex query in SQL that performs a count across two tables. The query should look like this:
SELECT
((SELECT COUNT(DISTINCT(pages.id)) AS `count`
FROM `pages`
INNER JOIN `pageRegions` ON pageRegions.pageId = pages.id
WHERE (MATCH (pages.name, pageRegions.contents) AGAINST ('+keyword*' IN BOOLEAN MODE))) +
(SELECT COUNT(documents.id) AS `count`
FROM `documents`
INNER JOIN `files` ON files.id = documents.file
WHERE (MATCH (documents.name,
files.name,
files.extracted_text) AGAINST ('+keyword*' IN BOOLEAN MODE)))) AS count
Unfortunately when I have the following code using Zend_Db the query includes a load of additional columns so the addition of both queries obviously fails:
$total_count_select = $PagesTable->getAdapter()
->query('((' . $pages_total_count_select . ') +
(' . $legal_resources_total_count_select . ')
) AS count');
Where $pages_total_count_select and $legal_resources_total_count_select are both Zend_Db_Select objects.
I have tried using the columns() method to specify the columns I want on each select object like so:
$legal_resources_total_count_select->columns('COUNT(documents.id) AS count');
But this just appears to append onto the select query rather than only returning the column specified.
So the Zend generated query ends up looking like this:
SELECT ((SELECT `pages`.*,
((1.3 * (MATCH(pages.name) AGAINST ('+keyword*' IN BOOLEAN MODE))) +
(0.8 * (MATCH(pageRegions.contents) AGAINST ('+keyword*' IN BOOLEAN MODE)))) AS `score`,
`pages`.`name` AS `page_name`,
`pages`.`id` AS `page_id`,
`pageRegions`.*,
COUNT(DISTINCT(pages.id)) AS `count`
FROM `pages`
INNER JOIN `pageRegions` ON pageRegions.pageId = pages.id
WHERE (MATCH (pages.name, pageRegions.contents) AGAINST ('+keyword*' IN BOOLEAN MODE))
ORDER BY `score` DESC)
+
(SELECT `documents`.*,
((1.3 * (MATCH(documents.title) AGAINST ('+keyword*' IN BOOLEAN MODE))) +
(0.8 * (MATCH(documents.short_description, files.NAME, files.extracted_text) AGAINST ('+keyword*' IN BOOLEAN MODE)))) AS `score`,
`files`.*,
COUNT(documents.id) AS `count`
FROM `documents`
INNER JOIN `files` ON files.id = documents.file
WHERE (MATCH (documents.title, documents.short_description, files.name, files.extracted_text) AGAINST ('+keyword*' IN BOOLEAN MODE))
ORDER BY `score` DESC)
) AS COUNT
How can I get rid of all the extra columns it is selecting?
You forgot one part of your code, where you construct the
$pages_total_count_selectand$legal_resources_total_count_select.You missed one parameter in the way to build these, which is the array of columns you want, if you do not give it it takes table.*.
So just check the way you create the select and add one argument with an empty array.
UPDATE:
So you do:
Just after that redo a
->from()call with your Zend_Db_Table ($this here) here you can specify the columns, so an empty array or the only one you want: