按组返回查询

时间:2012-12-13 18:55:54

标签: sql

说我有以下表格:

表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。 啤酒类型只有萨姆和拉里。

4 个答案:

答案 0 :(得分:1)

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

 select * 
 from table2 
 where name in (select name 
                from table 1 
                group by name);

答案 1 :(得分:0)

我认为这就是你想要的。

SELECT t1.Name, MIN(t2.Type)
FROM [Table 1] t1 JOIN [Table 2] t2 ON t1.Name = t2.Name
GROUP BY t1.Name

答案 2 :(得分: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以获取所有行。

答案 3 :(得分:0)

您可以通过询问表2中的条目总数与公共名称的数量相同以及表1中没有其他条目(名称)的类型来找到这些。。 / p>

在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