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

标签 sql

我有两个表如下:

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

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

现在我想创建一个查询来确定 List 的所有 ID它给出了类型字符串。

例如,

列表:
1 0 “一些文字”
1 1 "Moar 文本"
2 0 “福”
3 1 “酒吧”
3 2“巴巴兹”
4 0 "巴兹"
4 1 "FooBar"
4 2 "FooBarBaz"

类型:
0 “键 1”
1 个“ key 2”
2“ key 3”

给定输入“Key1”、“Key2”,查询应返回 1、4。

给定输入“Key2”、“Key3”,查询应返回 3、4。

给定输入“Key2”,查询应返回 1、3、4。

谢谢!

最佳答案

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

您必须根据放置在 where 子句中的键数来调整 have 子句。仅一个键的示例:
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

关于sql - 如何在sql中创建子集查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11811568/

相关文章:

sql - 在 T-SQL/SQL SERVER 中排序(或使用 ORDER BY 子句)而不考虑某些单词

android - 如何使用 SQL 查找特定时间范围内的条目总数?

sql - org.springframework.jdbc.UncategorizedSQLException : PreparedStatementCallback; uncategorized SQLException for SQL

sql - PostgreSQL 根据国家表解析数组中的国家

mysql - 如果不存在则插入行而不会出现死锁

sql - PostgreSQL 中的逆透视表

mysql - 我如何进行查询,只选择包含产品的类别?

java - 用Java解析SQL文件并获取语句和注释

mysql - 是否可以为整个表指定一个特定的 ID?

mysql - 从中获取丢失的数据应该是相同的 mysql 表