我在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
至少可以找到一次分配给所需组的。
现在我有一段$表达式的伪代码,如下所示:
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
)
3条答案
按热度按时间bbmckpt71#
您可以使用
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();
2o7dmzc52#
试试这个:
我不确定是否有
orWhereIn
方法,但此结构应该为您提供一个良好的起点。3wabscal3#
试试这个:
$users=db::select(“select count()from user where username='$username'and(username in(select username from user where group\u name in('a','b')having count()>1 group by username)或group\u name='c');