简体   繁体   English

如何在sql中创建子集查询?

[英]How to create a subset query in sql?

I have two tables as follows: 我有两张表如下:

CREATE List (
    id   INTEGER,
    type INTEGER REFERENCES Types(id),
    data TEXT,
    PRIMARY_KEY(id, type)
);

CREATE Types (
    id   INTEGER PRIMARY KEY,
    name TEXT
);

Now I want to create a query that determines all ids of List which has given type strings. 现在我想创建一个查询,确定给出类型字符串的List所有ID。

For example, 例如,

List:
1    0    "Some text"
1    1    "Moar text"
2    0    "Foo"
3    1    "Bar"
3    2    "BarBaz"
4    0    "Baz"
4    1    "FooBar"
4    2    "FooBarBaz"

Types:
0    "Key1"
1    "Key2"
2    "Key3"

Given the input "Key1", "Key2", the query should return 1, 4. 给定输入“Key1”,“Key2”,查询应返回1,4。

Given the input "Key2", "Key3", the query should return 3, 4. 给定输入“Key2”,“Key3”,查询应返回3,4。

Given the input "Key2", the query should return 1, 3, 4. 给定输入“Key2”,查询应返回1,3,4。

Thanks! 谢谢!

select distinct l.id 
from list l
inner join types t on t.id = l.type
where t.name in ('key1', 'key2')
group by l.id
having count(distinct t.id) = 2

You have to adjust the having clause to the number of keys you are putting in your where clause. 您必须将having子句调整为您在where子句中放置的键数。 Example for just one key: 只有一个键的示例:

select distinct l.id 
from list l
inner join types t on t.id = l.type
where t.name in ('key2')
group by l.id
having count(distinct t.id) = 1

SQlFiddle example SQlFiddle示例

You can use the following trick to extend Jurgen's idea: 您可以使用以下技巧来扩展Jurgen的想法:

with keys as (
    select distinct t.id
    from types t
    where t.name in ('key1', 'key2')
)
select l.id 
from list l join
     keys k
     on l.type = keys.id cross join
     (select count(*) as keycnt from keys) k
group by l.id
having count(t.id) = max(k.keycnt)

That is, calculate the matching keys in a subquery, and then use this for the counts. 也就是说,计算子查询中的匹配键,然后将其用于计数。 This way, you only have to change one line to put in key values, and you can have as many keys as you would like. 这样,您只需更改一行即可输入键值,并且您可以拥有任意数量的键。 (Just as a note, I haven't tested this SQL so I apologize for any syntax errors.) (就像一个注释,我没有测试过这个SQL,所以我为任何语法错误道歉。)

If you can dynamically produce the SQL, this may be one of the most efficent ways, in many DBMS: 如果您可以动态生成SQL,这可能是许多DBMS中最有效的方法之一:

SELECT l.id
FROM   List  l
  JOIN Types t1  ON t1.id = l.type
  JOIN Types t2  ON t2.id = l.type
WHERE  t1.name = 'Key1'
  AND  t2.name = 'Key2' ;

See this similar question, with more than 10 ways to get the same result, plus some benchmarks (for Postgres): How to filter SQL results in a has-many-through relation 看到这个类似的问题,有超过10种方法可以得到相同的结果,加上一些基准测试(对于Postgres): 如何过滤SQL结果的多次通过关系

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM