我正在使用全文搜索搜索3个不同的表,我需要检测结果来自哪个表。这就是我现在所拥有的:
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
我正在检测是否已设置page_title,如果没有设置议程标题等。 但结果始终来自第一个查询(页面)。因此,如果访问者搜索并查找新闻项,则在这种情况下它将显示为页面。
所以我的问题是;我究竟做错了什么?这是最好的方法吗?
提前致谢!
答案 0 :(得分:1)
尝试查询:
SELECT 'pages' AS used_table,id, title, MATCH(title) AGAINST(:search_term IN BOOLEAN MODE) AS score FROM pages WHERE MATCH(title) AGAINST(:search_term IN BOOLEAN MODE) UNION
SELECT 'agenda' AS used_table,id, title , MATCH(title) AGAINST(:search_term IN BOOLEAN MODE) AS score FROM agenda WHERE MATCH(title) AGAINST(:search_term IN BOOLEAN MODE) UNION
SELECT 'news' AS used_table,id, 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
并检查used_table字段以检查使用了巫婆表。
答案 1 :(得分:1)
当您使用UNIONs
时,请为每个表添加一个行列式列,只是一个常量,以便您知道每个条目来自哪个表。
SELECT source, id, title, score
FROM
(SELECT 'pages' AS source, id, title, MATCH(title) AGAINST(:search_term IN BOOLEAN MODE) AS score
FROM pages WHERE MATCH(title) AGAINST(:search_term IN BOOLEAN MODE)
UNION
SELECT 'agenda' AS source, id, title, MATCH(title) AGAINST(:search_term IN BOOLEAN MODE) AS score
FROM agenda WHERE MATCH(title) AGAINST(:search_term IN BOOLEAN MODE) UNION
SELECT 'news' AS source, id, 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
你还需要在整个组合集中将它包装在SELECT
到ORDER BY
中,就像我想的那样只能在最后一个表上排序。更改title
属性也不是一个好主意,因为UNION
的列名必须相同,否则它会将它们与第一个遇到的标题合并,或者只删空列名。 / p>