2011-05-22 83 views
0

我有以下表格:如何根據另一個表中的數據對mysql中的項目進行排序?

WORD_LIST:

id | word 
1 | ball 
2 | car 
3 | small 

items_word_match:

itemid | wordid | in_title | in_description 
1  | 1  | 1  | 0 //The word #1 occurs once in the title of the item 
1  | 3  | 0  | 2 //The word #3 occurs twice in the title of the item 
3  | 3  | 1  | 2 
2  | 1  | 1  | 0 

搜索:

wordid | importance 
1  | 1 
2  | 5 
3  | 2 //word #3 is more important than the word #1 but less so than word #2 

我想根據從關鍵字的項目進行排序搜索表以及關鍵字的重要性。
如果關鍵字在標題中的重要性應該增加1,如果出現2倍的單詞的重要性應該是重要的* 2

+0

沒有爲*壞*英文道歉。只要我們知道你的意思**,這不是問題。而且你的英語除了**之外根本不好。 – Johan 2011-05-22 20:03:16

回答

2

從丹尼斯或約翰這些問題的答案既不是正確的。相反,你可以使用這個:

select 
    itemid, 
    sum(word_importance) as item_importance 
from 
    (select 
     itemid, 
     search.wordid, 
     (
      in_title * (importance + 1) 
      + in_description * importance 
     ) as word_importance 
    from 
     items_word_match, 
     search 
    where 
     i.wordid = s.wordid 
    ) 
group by itemid 

正如約翰指出,你需要一個訂單條款添加到末尾,, order by item_importance desc

+1

您的查詢不按重要性排序,添加'order by'子句,因爲'group by'中的隱式排序是錯誤的。順便說一句,我並沒有試圖在正文中回答這個問題,而是總體上回答了標題中的問題。雖然看起來很漂亮。 – Johan 2011-05-22 20:20:55

1

今天感覺有點懶,所以我只是要去回答標題中的問題:

如何根據來自其他表的數據對項目進行排序?

您可以按任何標準對查詢結果進行排序。

SELECT word_list.* FROM word_list 
INNER JOIN search ON (search.wordid = wordlist.id) 
ORDER BY search.importance, word_list.id DESC 

請注意,這兩個表連接在一起所需的JOIN會對這在word_list表中的行選擇產生深遠的影響,但你需要做一個JOIN莫名其妙。
否則MySQL將不知道這兩個表之間的關係是什麼,並且不能對這些字段進行排序。

0

您的ORDER BY子句可以包含任何表的字段:

select table1.* 
from table1 
join table2 using (table1_id) 
order by table2.field, table1.field, etc. 
1
SELECT 
    i.itemid 
    , SUM(i.in_description * s.importance 
     + i.in_title * (s.importance + 1) 
     ) 
    AS item_importance 
FROM 
    items_word_match i 
     LEFT JOIN 
    search s 
      ON s.wordid = i.wordid 
GROUP BY 
    i.itemid 
ORDER BY 
    item_importance DESC 

更正:

我以前LEFT JOIN抓在search表中沒有出現某些單詞的情況。但後來的那些話的重要性似乎是適當的是0而不是NULL,使之和應改爲:

, SUM(i.in_description * COALESCE(s.importance, 0) 
     + i.in_title * COALESCE(s.importance, 1) 
     ) 
+0

+1最佳答案,請注意,您可以通過說出ORDER BY item_importance而不是ORDER BY SUM來縮短查詢(....# – Johan 2011-05-22 20:25:43

+0

@Johan:是的,thnx。我一直忘記,因爲你不能在另一個計算字段中使用別名。但你可以在'ORDER BY'中。 – 2011-05-22 20:29:48

相關問題