【问题标题】:How to fetch common item from two tables - Oracle如何从两个表中获取公共项目 - Oracle
【发布时间】:2021-07-21 21:23:59
【问题描述】:

场景 - 我的用户在多个项目上分配了不同的限制。这些限制在限制组中指定。有时会发生用户属于多个限制组的情况。有时,错误地为用户分配了对公共项目具有冲突限制的限制组。例如,用户 123 是限制组 A1 和 B1 的一部分,它们有一个共同的项目绿球,其中限制组 A1 有一个限制,即用户 123 每天只能访问 3 个绿球,而限制组 B1 说用户 123 只能访问每天 2 个绿球,从而导致冲突。我必须构建一个查询,以在存在冲突的情况下获取信息。每个用户都属于特定区域,因此将使用区域 ID 过滤结果。我的查询应该输出。

UserId, Common Item, Restriction Group Name, Restriction

表格

user - Id, userregionid
userRestriction - userId, restrictionGroup
restrictions- Item, restrictionGroup, restriction, interval // For example, Green Balls, Group A1, 3 , 1 (means 1 day)

我的努力-

select user.id, 
userRestriction.restrictionGroup,
restrictions.Item,
restriction.restriction, 
restriction.interval

from user left outer join userRestriction on user.Id = userRestriction.userId

left outer join restrictions on userRestriction.restrictionGroup = restriction.restrictionGroup

where user.useregionid= '12345'

group by userRestriction.userid, 
user.id, 
userRestriction.restrictionGroup,
restrictions.Item, 
restriction.restriction,
restriction.interval,user.userregionid
having count(userRestriction.restrictiongroup)>1

运行此查询我什么也没得到。这是不正确的,因为我有应该得到的数据。

在我的数据库中,我有 UserRestriction 表

UserId | RestrictionGroup

EID-999| A1
EID-888 | B1
EID-999 | C1

在限制表中

Item | RestrictionGroup| restriction | interval

GreenBalls| A1 | 1 | 1
Pen       | B1 |1  | 7
GreenBalls|C1  |1  |30

查询应该输出

EID-999 | GreenBalls | A1 | 1 | 1
EID-999 | GreenBalls | C1 | 1 |30 

用户表:


Id | userregionid

EID-999 | 12345
EID- 888 | 12345
D-900 | 2322
F-999 | 6767

查询应该只获取属于指定 userregionid 的用户。

【问题讨论】:

  • 请同时发布用户表的示例数据。
  • @AnkitBajpai 更新了我的问题
  • 空白结果的原因可能是在 User 表中您的 Id 为 E-999 而在 UserRestriction 中您的 Id 为 EID-999
  • 抱歉打错了,我为您输入了示例数据。更新了数据。

标签: oracle join group-by left-join outer-join


【解决方案1】:

我认为您的查询存在一些问题。您可以尝试以下查询 -

select U.id,
       UR.restrictionGroup,
       R.Item,
       R.restriction,
       R.interval
  from users U
  left outer join userRestriction UR on U.Id = UR.userId
  left outer join restrictions R on UR.restrictionGroup = R.restrictionGroup
 where U.userregionid = 12345
 group by U.id,
          UR.restrictionGroup,
          R.Item,
          R.restriction,
          R.interval
having count(UR.RestrictionGroup) >= 1

DB Fiddle

【讨论】:

  • 这个查询和我的一样。我试过了,它什么都没有。
  • 我认为Having子句是罪魁祸首。我已经更新了它。请立即尝试并告诉我结果。
  • 我在表格限制中添加了另一个项目INSERT INTO Restrictions VALUES('GreenPen', 'C1', 1, 30);。现在,查询也获取了这个值。但它不应该获取这个值。
  • 我更新了数据,它还显示了分配给 D1 组的员工的数据。但它不应该显示那个。可能是因为我们使用了左外连接。
猜你喜欢
  • 2014-06-14
  • 2019-12-22
  • 2014-07-11
  • 2022-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多