首页 > 解决方案 > SQL order by total of value by rows

问题描述

有没有一种方法可以返回包含行中的总列值,以按示例将其用于排序:

id  | title         | body_text_1           | body_text_2           | body_text_3           |
---------------------------------------------------------------------------------------------
1   |  History      | book of History       | movies                | Image                 |
2   |  Sport        | history               | book                  | Audio                 |
3   |  Cinema       | History               | History               | History               |
4   |  History      | classic               | History               | Audio                 |

我正在使用 LIKE %value% 如果我搜索单词History 结果将 id 3 显示为第一个,因为它在 3 列中有历史记录

第二个将是 1 和 4,因为它在 2 列中有历史记录

最后一个将是 2 因为它只在一列中有历史

结果 :

3
1
4
2

标签: phpmysqlsql

解决方案


您可以将布尔值添加到order by

order by (title = 'History') + (body_text_1 = 'History') +  (body_text_2 = 'History') + (body_text_34 = 'History') desc   

推荐阅读