【问题标题】:MYSQL: how to return value from column that has relation to values in another columnMYSQL:如何从与另一列中的值相关的列中返回值
【发布时间】:2018-11-04 12:45:43
【问题描述】:

我正在努力表达这一点,更不用说在 MYSQL 中执行了。如何返回 userId X 其中 userId.X 和 permissionId 在 (1,2,3,4,5,6,7,8) ?

下面的例子应该返回 6。

MariaDB [mailserver]> select * from user2permission;
+--------------+--------+
| permissionId | userId |
+--------------+--------+ 
|            1 |      5 |
|            1 |      6 |
|            2 |      6 |
|            2 |      7 |
|            3 |      6 |
|            4 |      6 |
|            5 |      6 |
|            6 |      6 |
|            7 |      6 |
|            8 |      6 |
+--------------+--------+

【问题讨论】:

标签: mysql sql


【解决方案1】:

可以使用 Group By 子句编写这种查询,并根据 where 子句中应用的过滤计算实例

SELECT userId
FROM user2permission 
WHERE permissionId  IN (1,2,3,4,5,6,7,8)
GROUP BY userId 
HAVING COUNT(*) = 8

【讨论】:

  • 谢谢 Rizwan。这是我需要的澄清。
  • @dom 注意这里的暗示(不是不合理的)是(userid,permissionid)是唯一的
【解决方案2】:

您只想显示拥有所有必需权限条目的用户。我想到了两个解决方案:

select *
from users
where userid in (select userid from user2permission where permissionid = 1)
  and userid in (select userid from user2permission where permissionid = 2)
  ...

select userid,
from user2permission
group by userid
having count(case when permissionid = 1 then 1 end) > 0
   and count(case when permissionid = 2 then 1 end) > 0
   ...

当我想到“春天”时,我的意思就是 = 不用多想 :-) 你应该使用 Rizwan 的聚合解决方案。

【讨论】:

  • 是的,弹跳可能会减少:-$
猜你喜欢
  • 2011-01-31
  • 2013-03-28
  • 1970-01-01
  • 2020-03-29
  • 1970-01-01
  • 2017-02-21
  • 1970-01-01
  • 1970-01-01
  • 2017-01-16
相关资源
最近更新 更多