mysql - 如何根据另一个查询结果进行查询

标签 mysql sql

我想知道如何基于另一个查询结果构建查询。

例如:

我有这个名为 groups 的表:

group_id | user_id | is_admin
  146    |    1    |    1
  146    |    3    |    1
  146    |    6    |    1
  146    |    7    |    1
  102    |    21   |    1
  105    |    174  |    1
  109    |    369  |    1

因此,我执行此查询以获取基于 user_id 的所有组

SELECT * FROM groups WHERE user_id = 6;

结果是?

group_id | user_id | is_admin
  146    |    6    |    1

但是,我现在想获取基于 group_id 的所有组。所以,我想 执行此查询:

 SELECT * FROM groups where group_id = 146;

所以,我有这个查询结果:

group_id | user_id | is_admin
  146    |    1    |    1
  146    |    3    |    1
  146    |    6    |    1
  146    |    7    |    1

在简历中,我想找到属于哪个组或用户,并选择包含其 group_id 的所有行

1 - 从 user_id = 6 的组中选择*;
2 - SELECT * FROM groups WHERE groups in (146,102, ...);

注意:user_id 可以属于多个组。

谢谢。

最佳答案

如果您只希望每个用户一个组(如示例数据中所示),请使用 = 和子查询:

select g.*
from groups g
where g.group_id = (select g2.group_id from groups g2 where g2.user_id = 6);

如果用户可以属于多个组,请使用 in:

select g.*
from groups g
where g.group_id in (select g2.group_id from groups g2 where g2.user_id = 6);

关于mysql - 如何根据另一个查询结果进行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56430038/

相关文章:

mysql - 在MySQL中将列填充到最大值?

php - 如何编写多个条件为 true 的 php If 语句(Condition#1=true、Condition#2=true、Condition#3=true)

javascript - Google Chart 中的 MySQL 日期时间

mysql - 如何从其他数据库插入值到mysql

c# - 选择 List<int> 中所有值的位置

c# - 填充我的下拉列表 C# asp.net

mysql - MySQL CASE 语句是否有优先级?

sql - 有没有办法将 JSON 对象数组与其他 View /表中的另一个 JSON 对象数组合并?

C#静态方法问题

sql - 将工作日的行组合在一起