mysql联合搜索(多个表)维护相关性

时间:2012-12-16 14:13:37

标签: php mysql

我有多个表,不同的列,相应地设置全文索引。如果我只想搜索一个表,因为得分会按相关性对数据进行排序,这没有问题。但是我有多个表,我使用UNION来表示这些sql SELECT语句如下:

$this->dbi->prepare("
    SELECT `id`,'".PRE."pages' as `table`, MATCH(`title`,`content`) AGAINST (?) AS `score` FROM `".PRE."pages` WHERE MATCH(`title`,`content`) AGAINST (?)
    UNION SELECT `id`,'".PRE."news' as `table`, MATCH(`title`,`content`) AGAINST (?) AS `score` FROM `".PRE."news` WHERE MATCH(`title`,`content`) AGAINST (?)
    UNION SELECT `id`,'".PRE."comments' as `table`, MATCH(`title`, `content`) AGAINST (?) AS `score` FROM `".PRE."comments` WHERE MATCH(`title`, `content`) AGAINST(?)
    UNION SELECT `id`,'".PRE."auction_auto' as `table`, MATCH(`manufacturer`,`model`,`location`,`other`,`contact`) AGAINST (?) AS `score` FROM `".PRE."auction_auto` WHERE MATCH(`manufacturer`,`model`,`location`,`other`,`contact`) AGAINST (?)
;")->...

我如何才能获得这些表的相关性?现在,无论分数数据将按照表格的顺序显示,我都会选择。

感谢。

For a possible solution by an autor himself see this link

1 个答案:

答案 0 :(得分:0)

两个选项:

  1. 创建一个视图,然后您可以通过从视图中进行选择来进行排序。
  2. 将您的查询放入(嵌套查询为as with table),并按顺序排序。请参阅:http://dev.mysql.com/doc/refman/5.0/en/from-clause-subqueries.html
  3. 以下是我自己的数据示例(仅用于示例目的):

    select * from
    (
      (select * from products where products_id >10)
      UNION
      (select * from products where products_id <= 10)
    )
    as SOURCE
    order by products_id
    

    因此,使用您自己的示例,它将类似于:

        $this->dbi->prepare("
    select * from 
    (
            SELECT `id`,'".PRE."pages' as `table`, MATCH(`title`,`content`) AGAINST (?) AS `score` FROM `".PRE."pages` WHERE MATCH(`title`,`content`) AGAINST (?)
            UNION SELECT `id`,'".PRE."news' as `table`, MATCH(`title`,`content`) AGAINST (?) AS `score` FROM `".PRE."news` WHERE MATCH(`title`,`content`) AGAINST (?)
            UNION SELECT `id`,'".PRE."comments' as `table`, MATCH(`title`, `content`) AGAINST (?) AS `score` FROM `".PRE."comments` WHERE MATCH(`title`, `content`) AGAINST(?)
            UNION SELECT `id`,'".PRE."auction_auto' as `table`, MATCH(`manufacturer`,`model`,`location`,`other`,`contact`) AGAINST (?) AS `score` FROM `".PRE."auction_auto` WHERE MATCH(`manufacturer`,`model`,`location`,`other`,`contact`) AGAINST (?)
    ) as allTables order by `id`;")