单个MySQL查询以选择具有彼此匹配的特定单元格的任何行

时间:2013-04-07 03:05:15

标签: mysql sql

标题有点令人困惑,所以让我解释一下。假设我有以下行:

type        name            seeds       size

fruit       apple           8           22
fruit       orange          8           14
fruit       raspberry       83          6
berry       pomegranate     201         19

我想要一个比较所有行的查询,并返回seeds与任何其他行匹配的所有行,并且类型为fruit。这可能吗?

1 个答案:

答案 0 :(得分:3)

试试这个:

SELECT DISTINCT t1.*
FROM table t1
INNER JOIN table t2 ON t2.seeds = t1.seeds
WHERE t1.type = 'fruit' AND t2.type = 'fruit' AND t1.name <> t2.name

修改

根据您的评论,要查找seeds匹配但type不匹配的项目,请尝试以下操作:

SELECT DISTINCT t1.*
FROM table t1
INNER JOIN table t2 ON t2.seeds = t1.seeds
WHERE t1.type <> t2.type