【问题标题】:Search sort by parameter match count in the query? PostgreSQL按查询中的参数匹配计数搜索排序? PostgreSQL
【发布时间】:2011-03-05 11:33:55
【问题描述】:

我正在 PostgreSQL 中进行搜索查询,我做的一件事是按匹配的参数数量对查询结果进行排序。我不知道如何做到这一点。有没有人有建议或解决方案?

 Table
 brand     color     type     engine
 Ford      Blue      4-door   V8
 Maserati  Blue      2-door   V12
 Saturn    Green     4-door   V8
 GM        Yellow    1-door   V4

 Current Query
 SELECT brand FROM table WHERE color = 'Blue' or type = '4-door' or engine = 'V8'

 Result Should Be
 Ford      (3 match)
 Saturn    (2 match)
 Maserati  (1 match)

【问题讨论】:

    标签: sql database postgresql search


    【解决方案1】:

    对于 Mysql,它看起来像这样,

    SELECT brand, 
    IF(color = 'Blue',1,0)+IF(type = '4-door', 1,0)+IF(engine = 'V8',1,0) 
       AS num_matches
    FROM table WHERE color = 'Blue' or type = '4-door' or engine = 'V8'
    

    仔细检查 PostgreSQL 的 IF 语法。 您也可以使用 CASE。

    【讨论】:

      【解决方案2】:

      我认为你应该能够做到:

      ORDER BY
          CASE WHEN color = 'Blue' THEN 1 ELSE 0 END +
          CASE WHEN type = '4-door' THEN 1 ELSE 0 END +
          CASE WHEN engine = 'V8' THEN 1 ELSE 0 END DESC
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-05-23
        • 1970-01-01
        • 2015-08-13
        • 1970-01-01
        • 1970-01-01
        • 2011-11-23
        相关资源
        最近更新 更多