doujiexi1824 2016-10-27 05:48
浏览 79

通过计算通过PDO / SQL相关的单词对搜索结果进行排名

I would like to create a search engine that displays results by ranking preset. The rating consists of two parts 1. The amount of post views (represented by POP [INT] in "post" table) and the amount of the words in the text itself (represented by TXT [STRING] in "post" table).

That is if there is a three-Results

//$search = 'apple macbook';
  1. 3 hits (POP) and 3 keywords related (2 MACBOOK, 1 APPLE found in TXT) = 6 - will be presented first
  2. 2 hits (POP) and 3 keywords related (1 MACBOOK, 1 APPLE found in TXT) = 5 - will be presented Second
  3. 2 hits (POP) and 1 keyword related (1 APPLE found in TXT) = 3 - will be presented Third

My code:

$search = isset($_GET['s']) ? htmlspecialchars($_GET['s']) : ''; 
$search = strtoupper($search);
$search = strip_tags($search); 
$search = trim($search);
$words = explode(' ', $search);
$words_condition = array();
$arguments = array();
foreach ($words as $word) {
    $words_condition[] = 'TXT LIKE ?';
    $arguments[] = '%'.$word.'%';
}

    $query = $db->prepare("SELECT * FROM `post` WHERE ".implode(" OR ",
    $words_condition)." ORDER BY POP DESC"); $query->execute($arguments);

About my table structure ("post" table) there are 4 Column...

  1. ID [INT] 2. SUB (the subject of the post) [STRING] 3. TXT (the body/full text) [STRING] 4. POP [INT] (hits of visit this post).
  • 写回答

1条回答 默认 最新

  • dtn55928 2016-10-27 12:26
    关注
    CREATE TABLE post (id INT, txt varchar(100), pop int);
    INSERT INTO post VALUES (1, "key key cle cle", 1);
    INSERT INTO post VALUES (2, "key key cle cle", 2);
    INSERT INTO post VALUES (3, "key key cle", 2);
    INSERT INTO post VALUES (4, "key cle cle", 1);
    
    SELECT *, (LENGTH(txt) - LENGTH(replace(txt, 'cle', '')))/LENGTH("cle") as cle, 
        (LENGTH(txt) - LENGTH(replace(txt, 'key', '')))/LENGTH("key") as key,
        (LENGTH(txt) - LENGTH(replace(txt, 'cle', '')))/LENGTH("cle")+(LENGTH(txt) - LENGTH(replace(txt, 'key', '')))/LENGTH("key") as nbKW
    FROM post 
    ORDER BY nbKW DESC, pop DESC;
    

    OK I test it and it works really well ! You have to adapt it with you argument !

    评论

报告相同问题?

悬赏问题

  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染