SQL 通过所有精确值查找 ID 的查询

SQL query for finding ID by all exact values

我有一个一直想不通的困境。我花了很多时间搜索 google 和 Whosebug,但没有找到任何东西。也许我只是不知道我应该搜索的术语。我正在尝试创建一个 SELECT 语句来确定仅提供列表值时使用了哪个列表。多个列表可能具有相同的值...

1.) 邮件列表:

2.) mailingLists table 结构

ListColumn PersonColumn
A Adam
A Brenda
A Carl
A Doug
A Edward
A Frank
B Adam
B Brenda
B Edward
C Doug
C Edward

3.) 用户向我提供了以下信息: Adam、Brenda、Edward。

如果只提供与多个列表相关联的人员,我如何确定用户邮寄到的确切列表?

我已经尝试了 "SELECT List FROM mailingLists... WHERE IN (SELECT...)" 语句的多种变体,但我总是得到与人员相关的所有列表(上面的列表 A 和 B),从来没有返回一个确切的列表(上面的列表 B)?

我是技术支持人员,不是开发人员之一,因此不可能更改任何 table 结构以使其更容易。

如果之前已经介绍过了,抱歉!任何帮助将不胜感激!谢谢!

P.S。数据库正在使用 SQL Anywhere 如果这会有所作为。

您可以使用以下两个查询来获取它

mysql> SELECT  LIST,count(*) FROM mailingLists WHERE Person IN ("Adam","Brenda","Edward") GROUP BY LIST;
+------+----------+
| LIST | count(*) |
+------+----------+
| A    |        3 |
| B    |        3 |
| C    |        1 |
+------+----------+
3 rows in set (0.00 sec)

mysql> (SELECT  LIST,count(*) FROM mailingLists  GROUP BY LIST) ;
+------+----------+
| LIST | count(*) |
+------+----------+
| A    |        6 |
| B    |        3 |
| C    |        2 |
+------+----------+
3 rows in set (0.00 sec)

根据匹配次数可以得到所需的列表

您可以使用聚合来做到这一点 having:

select list
from mailinglists
group by list
having count(*) = sum(case when person in ('Adam', 'Brenda', 'Edward') then 1 else 0 end);

这将获取恰好包含三个名称的列表,这些名称就是所提供的名称。所以这将 return 列出 B.

如果您同时想要列表 A 和 B(包含名称但可能具有其他名称的所有列表),则类似的方法可行:

select list
from mailinglists
where person in ('Adam', 'Brenda', 'Edward') 
group by list
having count(*) = 3;  -- the "3" here is the number of names provided by the user
with Search(Person) as (
    select 'Adam' union all
    select 'Brenda' union all
    select 'Edward'
)
select
from MailingLists ml left outer join Search s on s.Person = ml.PersonColumn
group by ml.ListColumn
having count(*) = count(s.Person) -- entire list matches up one to one
having count(s.Person) = (select count(*) from Search) -- all search persons found

这类似于 Gordon 的方法,但可能更通用一些,并且可以处理 match/search 上任意数量的名称。例如,您可以将 Search 列表替换为对另一个 table 的查询。 Select 两个 having 子句之一,具体取决于您想要的匹配项的性质。另一件需要注意的事情是搜索列表中的重复名称会弄乱结果。