简体   繁体   中英

mysql union search (multiple tables) maintaining a relevance

I have more than one table, with different columns, full text indexes are set accordingly. There is no problem if I would want to seach only one table as score would sort data by relevance. However I have multiple tables and I use UNION for these sql SELECT statements as following:

$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 (?)
;")->...

How can I have relevancy for these many tables? Now no matter of scores data will be displayed according to the order of table I do select.

Thanks.

For a possible solution by an autor himself see this link

Two options:

  1. Create a view that would allow you to then do sorting by selecting from the view.
  2. Put your query in from ( nested query as table with as), and order by. See: http://dev.mysql.com/doc/refman/5.0/en/from-clause-subqueries.html

Here is an example with my own data (only for example purposes):

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

So with your own example it would be something similar to:

    $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`;")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM