【问题标题】:Excluding results that have a field that is assigned to a non-unique field in a different table排除具有分配给不同表中的非唯一字段的字段的结果
【发布时间】:2018-04-20 09:28:46
【问题描述】:

我正在尝试从表 (tblRecords) 中进行选择,并排除具有在不同表 (tblPerson) 中重复的值的行。作为一个视觉示例:

当前表格:

 tblRecords:                    tblPerson:
+------------+-------------+   +------------+------------+
| CustomerID | OrderID     |   | PersonID   | UserID     |
+------------+-------------+   +------------+------------+
| 101        |           1 |   | 8          | 3004       |
| 18         |           7 |   | 5          | 81         |
| 8          |           1 |   | 19         | 100        |
| 100        |           2 |   | 19         | 101        |
+------------+-------------+   +------------+------------+

期望的输出:

+------------+-------------+
| CustomerID | OrderID     |
+------------+-------------+
| 18         |           7 |
| 8          |           1 |
+------------+-------------+

这是一个简化的示例,因此请原谅不良表设计的迹象。由于PersonID '19' 在tblPerson 中多次出现,我想排除来自tblRecords 的所有结果,其中CustomerID 与对应于重复PersonIDUserID 相同(因此排除100 和 101)。

我认为解决方案不是按重复值分组,而是在查询的 WHERE 子句中使用NOT EXISTS。这是我写的查询没有按预期工作:

SELECT *
FROM  tblRecords
WHERE NOT EXISTS (
    SELECT PersonID
    FROM tblPeople
    GROUP BY PersonID
    HAVING COUNT(PersonID) > 1
)

我不明白如何修复查询,因此它知道要从tblRecords 中排除结果,其中CustomerID 值出现在tblPerson 中重复的PersonID 旁边。目前,子查询选择我想要排除的确切值。我只是不知道他们是如何在 CustomerID 中被搜索到的。

【问题讨论】:

  • 编辑您的问题并提供示例数据和所需结果。这个问题相当荒谬,因为您似乎在描述中谈论一个表,但查询指的是两个。
  • 请阅读this,了解一些改进问题的技巧。
  • @GordonLinoff 我重写了这个问题。希望它更清楚。
  • @HABO 我重写了这个问题。希望它更清楚。

标签: sql sql-server tsql exists


【解决方案1】:

您可以在not exists() 查询的where 子句中添加相关性:

SELECT *
FROM  ISOW.dbo.tblRecords r
WHERE NOT EXISTS (
    SELECT PersonID
    FROM ISOW.dbo.tblPeople p
    where p.PersonID= r.CustomerID 
    GROUP BY PersonID
    HAVING COUNT(PersonID) > 1
)

对于更新后的问题,使用not exists()exists()

select r.CustomerID, r.OrderID
from  dbo.tblRecords r
where not exists (
    select PersonID
    from dbo.tblPeople p
    where p.UserID= r.CustomerID 
      and exists (
        select 1
        from dbo.tblPeople i
        where i.PersonID = p.PersonID
          and i.UserID <> p.UserID
      )
    )

rextester 演示:http://rextester.com/DNWK20907

返回:

+------------+---------+
| CustomerID | OrderID |
+------------+---------+
|         18 |       7 |
|          8 |       1 |
+------------+---------+

【讨论】:

  • 恭喜30k +1
  • @JuanCarlosOropeza 谢谢!看来你也离得不远了。
  • 虽然我稍微改变了我的问题,但您添加的 WHERE 子句真正回答了我的问题。谢谢!
  • @user7733611 乐于助人!
猜你喜欢
  • 1970-01-01
  • 2016-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-16
  • 2011-05-17
  • 1970-01-01
  • 2013-04-22
相关资源
最近更新 更多