php - SQL 按公式加权行

标签 php mysql sql search laravel-5

我正在尝试制作一个搜索表单来查找用户。

如何根据以下公式对行进行评分?

score = isInTheSameCityWithMe + isInTheSameStateWithMe + isInTheSameCountryWithMe

所以,如果我住在巴黎,应该把同样住在巴黎的人放在首位。

我的实现是这样的

<code>$users = \DB::table('users')->
                    select('name', 'id', 'city', 'country', 'avatar');
if(\Auth::user()->hasLocation()) {
            $weightString = '';
            if(\Auth::user()->hasLocationFullToCity())
                $weightString = 'CASE WHEN users.city = \''.\Auth::user()->city.'\' THEN 4 ELSE
                    CASE WHEN users.state = \''.\Auth::user()->state.'\' THEN 3 ELSE
                    CASE WHEN users.country = \''.\Auth::user()->country.'\' THEN 2 ELSE 1 END END END';

            elseif(\Auth::user()->hasLocationFullToState())
                $weightString = 'CASE WHEN users.state = \''.\Auth::user()->state.'\' THEN 3 ELSE
                    CASE WHEN users.country = \''.\Auth::user()->country.'\' THEN 2 ELSE 1 END END';

            elseif(\Auth::user()->country)
                $weightString = 'CASE WHEN users.country = \''.\Auth::user()->country.'\' THEN 2 ELSE 1 END END';
            $users->addSelect(\DB::raw($weightString.' AS score'))->orderBy('score', 'DESC');
        }

这给我一个查询

select `name`, `id`, `city`, `country`, `avatar`, CASE WHEN users.city = 'Cluj Napoca' THEN 4 ELSE CASE WHEN users.state = 'Cluj' THEN 3 ELSE CASE WHEN users.country = 'Romainia' THEN 2 ELSE 1 END END END AS score from `users` where `name` LIKE ?  order by `score` desc

有没有更好的办法?

最佳答案

单个 case 表达式要简单得多:

select `name`, `id`, `city`, `country`, `avatar`,
       (CASE WHEN users.city = 'Cluj Napoca' THEN 4 
             WHEN users.state = 'Cluj' THEN 3 
             WHEN users.country = 'Romainia' THEN 2
             ELSE 1
        END) AS score
from `users`
where `name` LIKE ? 
order by `score` desc

编辑:

如果你有一个特定的用户,那么它看起来像:

select u.name, u.id, u.city, u.country, u.avatar,
       (CASE WHEN u.city = u2.city THEN 4 
             WHEN u.state = u2.state THEN 3 
             WHEN u.country = u2.country THEN 2
             ELSE 1
        END) AS score
from `users` u join
     (select u.* from users u where u.name = $name) u2
     on u.name <> u2.name
where u.name LIKE ? 
order by score desc

关于php - SQL 按公式加权行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30713275/

相关文章:

php - 检查用户是否喜欢外部网页上的页面(facebook)

mysql - MySQL 嵌套循环中的多个游标

mysql - 生成范围内的数字——SQL

php - mysql left join好像不行

php - 即时将 php 页面转换为 pdf

PHP "php://input"与 $_POST

mysql - 打开的数据库连接数

mysql - 使用 SQL 从数据库过滤数据

mysql - 在 mysql 查询中排除由 "between"定义的值范围内的值

php - where in condition 代码点火器