MySQL sort by number of occurrences

前端 未结 3 1465
遥遥无期
遥遥无期 2021-02-09 15:28

I am doing a search in two text fields called Subject and Text for a specific keyword. To do this I use the LIKE statement. I have encount

3条回答
  •  离开以前
    2021-02-09 16:09

    You want SUM instead. Count will count how many records have non-null values, which means ALL matches and NON-matches will be counted.

    SELECT *, SUM(Text LIKE '%Keyword') AS total_matches
    ...
    ORDER BY total_matches
    

    SUM() will count up how many boolean true results the LIKE produces, which will be typecast to integers, so you get a result like 1+1+1+0+1 = 4, instead of the 5 non-nulls count.

提交回复
热议问题