如何根据另一个表中的数据对mysql中的项进行排序?

时间:2011-05-22 19:50:32

标签: mysql sorting

我有以下表格:

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

4 个答案:

答案 0 :(得分:2)

Denis或Johan的答案都不正确。相反,你可以使用它:

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 :(得分:1)

今天感觉有点懒,所以我只想回答标题中的问题:

  

如何根据另一个表中的数据对mysql中的项进行排序?

您可以按照您希望的任何标准对查询结果进行排序。

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将无法知道两个表之间的关系是什么,也无法对字段进行排序。

答案 2 :(得分: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

CORRECTION:

LEFT JOIN表中没有出现某些单词时,我使用了search。但是,这些单词的重要性似乎适合0而不是NULL,因此SUM应更改为:

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

答案 3 :(得分:0)

您的order by子句可以包含任何表中的字段:

select table1.*
from table1
join table2 using (table1_id)
order by table2.field, table1.field, etc.
相关问题