我目前有以下记录:
+----+-------------+-----------------+--------+-----------------+-------------+
| id | postal_code | program_type_id | gender | school_location | school_type |
+----+-------------+-----------------+--------+-----------------+-------------+
| 1 | 66202 | 2 | female | | |
| 2 | 67487 | 2 | male | rural | public |
| 3 | 68504 | 2 | female | rural | private |
| 4 | 67554 | 2 | female | rural | public |
| 5 | 67212 | 2 | female | urban | public |
+----+-------------+-----------------+--------+-----------------+-------------+
我还有以下记录:
mysql> select id, postal_code, program_type_id, gender, school_location, school_type from applications limit 1 offset 6;
+----+-------------+-----------------+--------+-----------------+-------------+
| id | postal_code | program_type_id | gender | school_location | school_type |
+----+-------------+-----------------+--------+-----------------+-------------+
| 7 | 66202 | 2 | female | urban | public |
+----+-------------+-----------------+--------+-----------------+-------------+
我必须以某种方式将这条记录7
与数据库中的记录进行匹配并给出分数。
评分:
匹配的 postal_code = 1000
点
匹配的program_type_id = 490
点
匹配性别 = 20
分
匹配学校类型
= 500 分
现在,我应该检索的记录应按以下顺序排列:
+----+-------------+-----------------+--------+-----------------+-------------+
| id | postal_code | program_type_id | gender | school_location | school_type |
+----+-------------+-----------------+--------+-----------------+-------------+
| 1 | 66202 | 2 | male | | | 1K points
| 3 | 68504 | 2 | female | rural | private | 520 points
| 2 | 67487 | 1 | male | rural | public | 490 points
| 4 | 67554 | 1 | female | rural | public | 20 points
| 5 | 67212 | 1 | female | urban | public | 20 points
+----+-------------+-----------------+--------+-----------------+-------------+
5 rows in set (0.00 sec)
请注意,3 超过了 2,因为匹配 program_type_id 和性别将获得 520 分,而仅匹配 school_type 将仅获得 500 分。在本例中,3 的分数高于 2 的分数。
现在,我的问题是,有谁知道如何做到这一点以及如何做到这一点?顺便说一句,这是 MySQL 5。
最佳答案
查看 mysql 中的 case 语句。您的构造将采用以下形式
select <fields that matter>, (case when tab1.program_type_id = applications.program_type_id then 490 when
tab1.postal= applications.postal then 1000 end )from tab1, applications where
tab1.a = applications.a or tab1.b = applications.b
当然,您需要将此查询中的列名更改为您的列名。
关于mysql - 根据特定值对记录进行排名的 SQL 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22241512/