UNION的替代方案或解决方案,不要手动订购数据

时间:2012-12-16 19:13:15

标签: mysql

这个问题与UNION的索引或替代方案有关。

在进一步的示例中,我们假设title textcontent fulltextindex

想象一下,我们有三个陈述

SELECT title as text FROM news ORDER BY score DESC
SELECT name as text FROM pages ORDER BY score DESC
SELECT content as text FROM comments ORDER BY score DESC

我们可以将它们组合起来(请注意我们手动订购它们)

SELECT title as text FROM news ORDER BY score DESC
UNION
SELECT name as text FROM pages ORDER BY score DESC
UNION
SELECT content as text FROM comments ORDER BY score DESC

现在我们有text我们可以打印,但订单将是1)新闻2)页面3)评论

这是非常糟糕的,因为我们希望那些订购方式不同,可能是得分

因此,我们可以将所有这些THREE SELECTS合并到ONE SELECT并对其进行排序

SELECT text FROM (
   SELECT title as text FROM news ORDER BY score DESC
   UNION
   SELECT name as text FROM pages ORDER BY score DESC
   UNION
   SELECT content as text FROM comments ORDER BY score DESC
) as combination

现在我们可以ORDER

score

同样,这非常糟糕,因为每个表的分数不是基于整个选择

所以,我们继续前进,我的问题就越来越近了。

下一步是介绍MATCH() and AGAINST(),我们写

SELECT text, MATCH(text) AGAINST ('anything') as total_score FROM (
       SELECT title as text FROM news ORDER BY score DESC
       UNION
       SELECT name as text FROM pages ORDER BY score DESC
       UNION
       SELECT content as text FROM comments ORDER BY score DESC
    ) as combination ORDER BY total_score DESC

我们完成了!如果没有MATCH(text)看起来不被编入全文,那么一切都应该是完美的。

出现错误:找不到与列列表匹配的FULLTEXT索引

现在消费来了,可能还剩下什么,但不知何故让text成为FULLTEXT。不幸的是,数据库中没有text这样的列,比如说你无法在phpmyadmin中找到它FULLTEXT那样。

我想进一步扩展name as text以使其接近name as text type fulltext或类似的东西,这是我在任何地方都找不到的。

请帮帮我,我想听听,也许还有另一种方法可以解决这种情况?我不知道。我会非常感激。

1 个答案:

答案 0 :(得分:2)

使用UNION ALL代替UNION

UNION 排序联合结果集会丢弃重复项(如果有)。

UNION ALL保留所选的订单(并保留重复项,如果有的话)