0

我有一些 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 的 2 个字段:

公司名称 | 联系人姓名

和表格新闻的2个字段:

新闻标题 | 新闻内容

并一举将结果按相关性排序。我怎样才能将这些表格合并到我的结果中?

4

1 回答 1

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

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

于 2013-02-25T18:03:36.680 回答