我在 MySQL 中有一个表,其中包含 group_name
和 username
,如下所示:
ID|group_name|username
----------------------
1 | A | user1
----------------------
2 | B | user2
----------------------
3 | C | user1
...
我有一些如下所示的逻辑表达式:
(A & B) || C
这意味着,如果我正在搜索某个用户,则该用户应该同时位于 A 组和 B 组中,或者位于 C 组中。
我必须在 Laravel 中使用自定义表达式检查用户,我的查询将如下所示:
return DB::table('assigned_groups')->where($expression)->where('username', $username)->count();
其中 $expression
是我用原始 SQL 编写的逻辑表达式,我猜。我必须检查是否可以找到某些 $username
至少一次分配给所需的组。
现在我只有一段 $expression 的伪代码,如下所示:
select count(*)
having (
(count(select(*) where group_name = A) > 0
and count(select(*) where group_name = B) > 0)
or count(select(*) where group_name = C) > 0
)
如何正确编写此表达式?我应该如何更改 Laravel 查询和 $expression
本身?
UPD:现在我的 SQL 看起来像这样,几乎就是这样
SELECT count(*) FROM `assigned_groups`
where username = 'user1'
having (
(count(case group_name when 'A' then 1 else null end) > 0
and count(case group_name when 'B' then 1 else null end) > 0)
or count(case group_name when 'C' then 1 else null end) > 0
)
最佳答案
您可以使用havingRaw
编写原始表达式
DB::table('assigned_groups')
->where('username', $username)
->havingRaw("(count(case group_name when 'A' then 1 else null end) > 0
and count(case group_name when 'B' then 1 else null end) > 0)
or count(case group_name when 'C' then 1 else null end) > 0")
->count();
或更短的使用 sum()
DB::table('assigned_groups')
->where('username', $username)
->havingRaw("(sum(group_name ='A') > 0 and sum(group_name = 'B') > 0) or sum(group_name = 'C') > 0")
->count();
关于mysql - 为多个计数编写自定义 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50331835/