选择至少与列表中的所有项匹配的记录

时间:2018-03-03 21:30:50

标签: mysql sql

假设我有以下数据库表:

ID | Name    | Type     | Value|
--- --------- ---------- ------
1  | First   | A        | 10   |
2  | First   | B        | 20   |
3  | First   | C        | 30   |
4  | First   | D        | 40   |
5  | Second  | A        | 10   |
6  | Second  | B        | 20   |

并返回上一个查询:

ID | Name    | Type     | Value|
--- --------- ---------- ------
1  | Third   | A        | 10   |
2  | Third   | B        | 20   |
3  | Third   | C        | 30   |

我的问题是: 查询第一个表并获取至少在上一个查询中返回的所有类型的所有记录的最佳方法是什么?

在上面的示例中,名称“Third”具有类型AB C.使用这些作为列表,我想仅检索“First”记录(“First”具有ABCD)而不是“Second”(作为“第二个“只有AB - 缺少C”。

IN语句匹配eveything,我希望查询至少匹配“type”列表中的所有项目。 列表不一定来自sql语句,但可以提供

编辑:我正在使用MySQL

1 个答案:

答案 0 :(得分:0)

在标准SQL中,您可以使用joingroup by进行一些过滤。以下假设type对于每个表中的每个名称都是唯一的:

with prevq as (
      . . .
     )
select t.name
from t join
     prevq
     on t.type = prevq.type
group by t.name
having count(*) = (select count(*) from prevq);

编辑:

MySQL不支持CTE(8.0之前)。这很容易做到:

select t.name
from t join
     (<your query here>) prevq
     on t.type = prevq.type
group by t.name
having count(*) = (select count(*) from (<your query here>) prevq);