Mysql 如何在sql中检查一个集合是否是另一个集合的子集

Mysql 如何在sql中检查一个集合是否是另一个集合的子集,mysql,sql,sql-server,count,relational-division,Mysql,Sql,Sql Server,Count,Relational Division,DDL的文本: CREATE TABLE Recipe1( Ingredient varchar(10) ); INSERT INTO Recipe1(Ingredient) VALUES('Flour'),('Egg'),('Sugar'); CREATE TABLE Recipe2( Ingredient varchar(10) ); INSERT INTO Recipe2(Ingredient) VALUES('Egg'),('Sugar'); 我想检查配方2是否是配方1

DDL的文本:

CREATE TABLE Recipe1(
    Ingredient varchar(10)
);
INSERT INTO Recipe1(Ingredient) VALUES('Flour'),('Egg'),('Sugar');
CREATE TABLE Recipe2(
    Ingredient varchar(10)
);
INSERT INTO Recipe2(Ingredient) VALUES('Egg'),('Sugar');
我想检查配方2是否是配方1的子集,我想让SQL返回一个布尔值,我该怎么做? 我发现ORACLE支持一个名为SUBSET的函数:

但我找不到SQL Server甚至MySQL的等效版本。我希望得到SQL Server的答案

我们的讲师使用了以下代码: 配方1包含配方2,但不起作用。
另外,我没有使用或计划使用全文搜索,所以我需要一种解决方法。

假设上面的配方是表,那么如果Recipe2是Recipe1的子集,那么下面的查询将产生0计数

选择计数*作为cnt 从…起 从Recipe2中选择* 除了 从Recipe1中选择*作为x 请参阅:

在MySql中,您可以使用EXISTS和aggregation:

SELECT MIN(EXISTS (SELECT 1 FROM Recipe1 r1 WHERE r1.col1 = r2.col2)) AS is_subset
FROM Recipe2 r2
或不存在:


请参阅。

左连接也应起作用

Select count(*) ct 
from Recipe2 r2 
left join Recipe1 r1 on r2.Ingredient = r1.Ingredient
where r1.Ingredient is null
MS SQL Server:

如下图所示,可以使用Join和Case

SELECT CASE WHEN COUNT(R1.C1)=COUNT(R2.C1) THEN '1' 
ELSE '0' END AS IS_SUBSET
FROM (VALUES ('Flour'),('Egg'),('Sugar'))R1(C1)
RIGHT JOIN (VALUES ('Egg'),('Sugar'))R2(C1)
ON R1.C1=R2.C1
SQL Fiddle演示链接:

一种简单的方法是使用左连接和计数:

这将在某种程度上支持布尔值的数据库(如MySQL)中起作用。更可移植的方法是在外部查询中使用case:

select case when count(*) = count(r2.id) then 1 else 0 end as is_subset
from recipe1 r1
left join recipe2 r2 on t1.id = t.id

Recipe1和Recipe2是表吗?是的,它们是表。它在最后一个括号中给了我一个语法错误,我不明白为什么。错误消息是怎么说的?哦,我现在明白了,它必须有一个名称,否则会返回一个引用为x的错误。这是SQL Server语法TSQL。我看到你也有一个MySQL标签。MYSQL没有一个等价的。请参阅:了解MySQL的替代解决方案。
select (count(*) = count(r2.id)) as is_subset
from recipe1 r1
left join recipe2 r2 on t1.id = t.id
select case when count(*) = count(r2.id) then 1 else 0 end as is_subset
from recipe1 r1
left join recipe2 r2 on t1.id = t.id