2012-12-16 70 views
3

我有多個表,不同的列,全文索引相應地設置。如果我想只搜索一個表格,因爲分數會按相關性排序數據,所以沒有任何問題。不過我有多個表,我用UNION這些SQL語句SELECT如下:mysql聯合搜索(多表)保持相關性

$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

回答

0

兩個選項:

  1. 創建一個視圖,將允許你做,然後從視圖中選擇排序。
  2. 將你的查詢放在from(嵌套查詢as as table),並按順序排列。請參閱:http://dev.mysql.com/doc/refman/5.0/en/from-clause-subqueries.html

這裏是我自己的數據(僅作示例)的例子:

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

select * from 
(
    (select * from products where products_id >10) 
    UNION 
    (select * from products where products_id <= 10) 
) 
as SOURCE 
order by products_id 
用自己的例子這將是類似的東西

所以