您可以通过询问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