1

假设我有以下表格:

表格1

Name     Food 
______________
Sam      Chips
Tom      Chips
Larry    Chips

表 2

Name     Type
_____________
Sam      Dip
Tom      Dip
Larry    Dip
Marry    Soda
Peter    Soda
Sam      Soda
Larry    Soda
Sam      Beer
Larry    Beer

是否可以退货

Name    Type
____________
Sam     Dip
Tom     Dip
Larry   Dip

使用名称表 1 作为一个组并让该组在表 2 中完全匹配?

Soda Type 不匹配,因为它有 Marry、Peter、Sam、Larry。Beer Type 只有 Sam 和 Larry。

4

4 回答 4

1

如果我正确理解了您的问题,您可以使用这样的子查询。

 select * 
 from table2 
 where name in (select name 
                from table 1 
                group by name);
于 2012-12-13T19:05:53.857 回答
0

我想这就是你想要的。

SELECT t1.Name, MIN(t2.Type)
FROM [Table 1] t1 JOIN [Table 2] t2 ON t1.Name = t2.Name
GROUP BY t1.Name
于 2012-12-13T19:02:13.073 回答
0

您可以通过询问Table2 中的条目总数与常用名称的数量相同且 Table1 中没有其他条目(名称)的类型来找到这些。

在 SQL 中:

SELECT Table2.Name, Table2.Type
FROM
(
  SELECT Type
  FROM (SELECT DISTINCT Type FROM Table2) AS types
  WHERE (
    SELECT COUNT(*)
    FROM Table2 i2
    JOIN Table1 i1 ON i1.Name = i2.Name
    WHERE i2.Type = types.Type
  ) = (
    SELECT COUNT(*)
    FROM Table2 i2
    WHERE i2.Type = types.Type
  )
  AND (
    SELECT COUNT(*)
    FROM Table1
  ) = (
    SELECT COUNT(*)
    FROM Table2 i2
    WHERE i2.Type = types.Type
  )
) AS result
JOIN Table2 ON result.Type = Table2.Type

在行动中看到它:http ://sqlfiddle.com/#!2/8d50e/1

在 MySQL 中,您可以使用GROUP_CONCAT函数来进行更短且更易于阅读的查询:

SELECT Table2.Name, Table2.Type
FROM
(
  SELECT Type
  FROM (SELECT DISTINCT Type FROM Table2) AS types
  WHERE (
    SELECT GROUP_CONCAT(Name ORDER BY Name)
    FROM Table2 i2
    WHERE i2.Type = types.Type
  ) = (
    SELECT GROUP_CONCAT(Name ORDER BY Name)
    FROM Table1
  )
) AS result
JOIN Table2 ON result.Type = Table2.Type

请注意group_concat_max_len

演示:http ://sqlfiddle.com/#!2/af700/1

您是否真的要匹配整个 Table1 并不是很清楚,但上述解决方案可以很容易地扩展到 Food 和 Type 的每个匹配组合:

SELECT result.Food, Table2.Name, result.Type
FROM
(
  SELECT Type, Food
  FROM (SELECT DISTINCT Type, Food FROM Table2 JOIN Table1) AS combinations
  WHERE (
    SELECT COUNT(*)
    FROM Table2 i2
    JOIN Table1 i1 ON i1.Name = i2.Name
    WHERE i2.Type = combinations.Type
    AND i1.Food = combinations.Food
  ) = (
    SELECT COUNT(*)
    FROM Table2 i2
    WHERE i2.Type = combinations.Type
  )
  AND (
    SELECT COUNT(*)
    FROM Table2 i2
    WHERE i2.Type = combinations.Type
  ) = (
    SELECT COUNT(*)
    FROM Table1 i1
    WHERE i1.Food = combinations.Food
  )
) AS result
JOIN Table2 ON result.Type = Table2.Type

演示:http ://sqlfiddle.com/#!2/d4d4b/1

于 2012-12-13T19:35:32.483 回答
0

使用完全外连接,然后检查是否没有引入其他任何内容。以下查询获取匹配的“类型”:

select t2.type
from table1 t1 full outer join
     table2 t2
     on t1.name = t2.name
group by t2.type
having count(*) = count(t1.name) and -- all t1.names match
       count(*) = count(t2.name)     -- all t2.names match
       count(*) = (select count(*) from table1) -- all are present

这假定没有重复的名称。distinct如有必要,明智地使用可以解决该问题。

一旦你有了类型,你就可以加入到 table2 来获取所有的行。

于 2012-12-13T19:10:25.780 回答