为多个计数编写自定义sql查询

t98cgbkg  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(488)

我在mysql中有一个表,包含 group_name 以及 username ,如下所示:

  1. ID|group_name|username
  2. ----------------------
  3. 1 | A | user1
  4. ----------------------
  5. 2 | B | user2
  6. ----------------------
  7. 3 | C | user1
  8. ...

我有这样的逻辑表达式:

  1. (A & B) || C

也就是说,如果我在搜索某个用户,这个用户应该同时在a组和b组中,或者在c组中。
我必须在laravel中检查具有自定义表达式的用户,我的查询将如下所示:

  1. return DB::table('assigned_groups')->where($expression)->where('username', $username)->count();

哪里 $expression 是用原始sql写的逻辑表达式。我得检查一下 $username 至少可以找到一次分配给所需组的。
现在我有一段$表达式的伪代码,如下所示:

  1. select count(*)
  2. having (
  3. (count(select(*) where group_name = A) > 0
  4. and count(select(*) where group_name = B) > 0)
  5. or count(select(*) where group_name = C) > 0
  6. )

如何正确地写出这个表达式?我应该如何更改我的laravel查询和 $expression 它自己?
upd:现在我的sql看起来是这样的,它几乎是什么东西

  1. SELECT count(*) FROM `assigned_groups`
  2. where username = 'user1'
  3. having (
  4. (count(case group_name when 'A' then 1 else null end) > 0
  5. and count(case group_name when 'B' then 1 else null end) > 0)
  6. or count(case group_name when 'C' then 1 else null end) > 0
  7. )
bbmckpt7

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();

  1. 或更短时间使用 `sum()` ```
  2. DB::table('assigned_groups')
  3. ->where('username', $username)
  4. ->havingRaw("(sum(group_name ='A') > 0 and sum(group_name = 'B') > 0) or sum(group_name = 'C') > 0")
  5. ->count();
2o7dmzc5

2o7dmzc52#

试试这个:

  1. return DB::table('assigned_groups')
  2. ->where('username', $username)
  3. ->andWhere(function($query) use ($groupAandB, $groupC) {
  4. $query->whereIn('group_name', $groupAandB)
  5. ->orWhereIn('group_name', $groupC);
  6. })
  7. ->count();

我不确定是否有 orWhereIn 方法,但此结构应该为您提供一个良好的起点。

3wabscal

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');

相关问题