用于按所有精确值查找ID的SQL查询

时间:2016-06-24 17:00:21

标签: sql sqlanywhere

我有一个我无法弄清楚的困境。我花了很多时间搜索谷歌和stackoverflow,但无法找到任何东西。也许我只是不知道我应该搜索的术语。我试图创建一个SELECT语句来确定在仅提供列表值时使用了哪个列表。多个列表可能具有相同的值...

1。)邮件列表:

  • 名单A:Adam,Brenda,Carl,Doug,Edward,Frank
  • 名单B:Adam,Brenda,Edward
  • 名单C:Doug,Edward

2。)mailingLists表结构

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)?

我在技术支持方面,而不是开发人员之一,所以不可能改变任何表结构以使其更容易。

如果已经覆盖了对不起!任何帮助将不胜感激!谢谢!

P.S。数据库正在使用SQL Anywhere,如果这会产生影响。

3 个答案:

答案 0 :(得分:2)

您可以使用聚合和having

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

这会获得具有三个名称的列表,这些名称是提供的名称。所以这将返回列表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

答案 1 :(得分:0)

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

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)

根据匹配计数,您可以获得所需的列表

答案 2 :(得分:0)

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

这类似于戈登的方法,但可能更通用,可以处理任意数量的名称来匹配/搜索。例如,您可以将Search列表替换为另一个表上的查询。根据所需匹配项的性质,选择两个having子句中的一个。另外需要注意的是,搜索列表中的重复名称会使结果变得混乱。