UNION SELECT to get ID's from news and page (A database error occurred: Every derived table must have its own alias)

StackOverflow https://stackoverflow.com/questions/22930782

  •  29-06-2023
  •  | 
  •  

Question

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?

Was it helpful?

Solution

You say:

Unknown column 'news_item.id' in 'field list'. It exists. Definitely.

But it is not true. Your columns are nId, title and content:

SELECT 
`news_item`.`id` as nId,   #nId
`news_item`.`title`,       #title
`news_item`.`content`      #content
FROM `news_item` ni

OTHER TIPS

You should create an alias for subquery:

SELECT 
    *
FROM(
        SELECT `news_item`.`id` as nId, `news_item`.`title`, news_-...
        UNION 
        SELECT `page_item`.`id` as pId, `page_item`.`title`, page_it...
)   T  <---- here!!!
WHERE
    " . implode(" OR ", $searchTerms) . "
LIMIT
    " . $scope

Use alias name rather than news_item

Like myAlias.nId=123 or myAlias.title like '%word%'

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top