I'm trying to get the ID's of found items via a custom query. To avoid double results because of searching in 2 tables I understood that I should use UNION.
I wrote this little query:
SELECT * FROM( SELECT `news_item`.`id` as nId, `news_item`.`title`, `news_item`.`content` FROM `news_item` ni UNION SELECT `page_item`.`id` as pId, `page_item`.`title`, `page_item`.`content` FROM `page_item` pi ) WHERE `news_item`.`title` LIKE '%serious%' OR `news_item`.`content` LIKE '%serious%' OR `page_item`.`title` LIKE '%serious%' OR `page_item`.`content` LIKE '%serious%' LIMIT 0, 4
Which results in an SQL error: A database error occurred: Every derived table must have its own alias
I've tried using aliasses(As ni and pi. Also for the select values(ie. ni.title).) and tried without aliases, to no avail.
Here's the PHP:
$searchTerms = array();
foreach($searchWords as $word){
$searchTerms[] = "`news_item`.`title` LIKE '".$word."'";
$searchTerms[] = "`news_item`.`content` LIKE '".$word."'";
$searchTerms[] = "`page_item`.`title` LIKE '".$word."'";
$searchTerms[] = "`page_item`.`content` LIKE '".$word."'";
}
$newsAndPageItemsQry = "
SELECT
*
FROM(
SELECT `news_item`.`id` as nId, `news_item`.`title`, `news_item`.`content` FROM `news_item` ni
UNION
SELECT `page_item`.`id` as pId, `page_item`.`title`, `page_item`.`content` FROM `page_item` pi
)
WHERE
" . implode(" OR ", $searchTerms) . "
LIMIT
" . $scope;
Instant edit: When I give the initial FROM
an alias I get the database error: A database error occurred: Unknown column 'news_item.id' in 'field list'
. It exists. Definitely.
My question basically: How can I search in page_item and news_item to get the ID's for my keywords in title and content without getting duplicate results?