2015-06-08 57 views
2

我正在嘗試使用搜索表單來查找用戶。按公式計算的SQL重量行

我如何根據以下公式計算行數?

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 

查詢是否有更好的辦法?

回答

1

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