我正在使用 Laravel php 和 sql 创建一个推荐系统。用户在注册期间输入值,这些值存储在用户表中。
这是我的用户表架构,任何具有推荐名称格式的字段,例如,recommendationLocation 是系统应搜索的用户的位置。
TABLE `users` (
`id` (int),
`username` (varchar),
`email` (varchar),
`password` (varchar),
`age` (varchar),
`location` (varchar),
`country` (varchar),
`userType` (varchar),
`religion` (varchar),
`variable1` (varchar),
`variable2` (varchar),
`recommendationAge` (varchar),
`recommendationLocation` (varchar),
`recommendationReligion` (varchar),
`recommendationVariable1` (varchar),
`recommendationVariable2` (varchar),
`recommendationUserType` (varchar),
`recommendationHairColor` (varchar),
`recommendationCountry` (varchar),
)
以下语句是完美的直接用户匹配,但并非所有用户都会输入相同的信息。我的问题是,由于有大量的组合,我必须考虑很多不同的变量。因为我希望即使用户没有某些匹配信息,仍然能够找到用户。例如,该语句只能有一个匹配字段,但查询仍然返回具有该匹配字段的用户名。
$recommendationQuery = DB::table('users')
->select('username')
->where('id', '!=', Auth::id()) // Can't be the current Auth User Details
->where('age', '=' , Auth::user()->recommendationAge) // This is a required where clause for all statements
->where('location', '=', Auth::user()->recommendationLocation) // This is a required where clause for all statements
->where('religion', '=', Auth::user()->recommendationReligion)
->where('variable1', '=', Auth::user()->recommendationVariable1)
->where('variable2', '=', Auth::user()->recommendationVariable2)
->where('age', '=', Auth::user()->recommendationAge)
->where('location', '=', Auth::user()->recommendationLocation)
->where('country', '=', Auth::user()->recommendationCountry)
->where('hairColor', '=', Auth::user()->recommendationHairColor)
->get();
有没有其他更有效的方法? 谢谢
最佳答案
当前您的代码生成类似于以下 SQL 的内容:
SELECT username
FROM users
WHERE
id =! ? AND age = ? AND location = ?
AND religion = ? AND variable1 = ? AND ...
要使用户匹配,需要满足 WHERE
子句中的所有条件。
据我了解,您正在尝试将强制性条件与可选条件分开,例如:
SELECT username
FROM users
WHERE
id =! ? AND age = ? AND location = ?
AND (
religion = ? OR variable1 = ? OR ...
)
通过此查询,用户需要匹配 id
、age
和 location
以及 any< 的 3 个强制条件/em> 可选条件(宗教
、variablbe1
、...)。
要实现这一目标,您可以利用 Lavarel parameter grouping ,例如:
$recommendationQuery = DB::table('users')
->select('username')
->where('id', '!=', Auth::id()) // Can't be the current Auth User Details
->where('age', '=' , Auth::user()->recommendationAge) // This is a required where clause for all statements
->where('location', '=', Auth::user()->recommendationLocation) // This is a required where clause for all statements
->where(function ($query) {
$query->where('religion', '=', Auth::user()->recommendationReligion)
->orWhere('variable1', '=', Auth::user()->recommendationVariable1)
->orWhere('variable2', '=', Auth::user()->recommendationVariable2)
->orWhere('age', '=', Auth::user()->recommendationAge)
->orWhere('location', '=', Auth::user()->recommendationLocation)
->orWhere('country', '=', Auth::user()->recommendationCountry)
->orWhere('hairColor', '=', Auth::user()->recommendationHairColor)
})
->get();
关于php - 如何使用SQL比较多个字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54505476/