MySQL:在搜索中组合多个表

时间:2013-02-25 16:10:25

标签: mysql

我有一些SQL搜索网站的内容表并根据相关性返回结果:

SELECT *, 
( (1.3 * (MATCH(strTitle) AGAINST ('+query+string' IN BOOLEAN MODE))) + (0.6 * (MATCH(txtContent) AGAINST ('+query+string' IN BOOLEAN MODE)))) AS relevance 
FROM content 
WHERE (MATCH(strTitle,txtContent) AGAINST ('+query+string' IN BOOLEAN MODE) ) 
ORDER BY relevance DESC 

我需要扩展它以包括其他2个表。

我需要搜索一个表trade_members的两个字段:

  

company_name | CONTACT_NAME

和表新闻的2个字段:

  

news_title | news_content

并按照相关性一举将结果带回来。我怎样才能将这些表格纳入我的结果?

1 个答案:

答案 0 :(得分:0)

解决方案是三个选择的UNION。但是让我们首先解释它们。

到目前为止,你已经

SELECT *, {formula} AS relevance FROM content WHERE {cond} ORDER BY relevance DESC

您现在需要另外两个选择:

SELECT *, {formula} AS relevance FROM trade_members WHERE {cond} ORDER BY relevance DESC
SELECT *, {formula} AS relevance FROM news WHERE {cond} ORDER BY relevance DESC

如果单独运行这三个语句,您将看到它们返回不同的列。然后,您必须统一这些列。如果没有关于表结构的更多细节,我只能给你一些看起来像什么的提示。

SELECT 'content' as type, contentID as id, strTitle     as title, txtContent   as content, {formula} AS relevance FROM content WHERE {cond} ORDER BY relevance DESC
SELECT 'member'  as type, memberID  as id, company_name as title, contact_name as content, {formula} AS relevance FROM trade_members WHERE {cond} ORDER BY relevance DESC
SELECT 'news'    as type, newsID    as id, news_title   as title, news_content as content, {formula} AS relevance FROM news WHERE {cond} ORDER BY relevance DESC

现在所有三个选择都应该给你一个看起来相似的结果 - 更重要的是:你应该看到所有三个选择相同的列名,每一行应该允许你识别它代表的数据库中的哪些数据,例如:这是内容17,即公司33,即新闻1776。

现在你可以在这三个方面建立联盟:

(1st select) UNION (2nd select) UNION (3rd select) ORDER BY relevance DESC

请注意,但这可能相当慢,因为您实际上正在创建需要进行文件排序的四个临时表...您可以尝试如何摆脱排序这三个基本选择会影响性能 - 因为它们实际上并不需要。