I am searching through 3 different tables with fulltext search and I need to detect which table the result is coming from. This is what I have now:
SELECT id, title AS page_title, MATCH(title) AGAINST(:search_term IN BOOLEAN MODE) AS score FROM pages WHERE MATCH(title) AGAINST(:search_term IN BOOLEAN MODE) UNION
SELECT id, title AS agenda_title, MATCH(title) AGAINST(:search_term IN BOOLEAN MODE) AS score FROM agenda WHERE MATCH(title) AGAINST(:search_term IN BOOLEAN MODE) UNION
SELECT id, title AS news_title, MATCH(title) AGAINST(:search_term IN BOOLEAN MODE) AS score FROM news WHERE MATCH(title) AGAINST(:search_term IN BOOLEAN MODE) ORDER BY score ASC
I’m detecting if the page_title has been set and if not if the agenda title has been set etc.
But the result is always from the first query (pages). So if a visitor would search and find a news item, it would display as a page in this case.
So my question is; What am I doing wrong? And is this the best way to do it?
Thanks in advance!
When you are using
UNIONslike that, add a determinant column, just a constant, to each table, so that you know what table each entry comes from.You will also need to wrap it in a
SELECTtoORDER BYover the whole combined set, the way you had it would only order on the last table I think. Changing thetitleattribute is not a good idea either, as the column names need to be the same for aUNIONor it will merge them with the first encountered title, or just blank the column name.