2

我有这张桌子:

id type otherid
1   4     1234
2   5     1234
3   4     4321

如您所见,有 3 条记录,其中 2 条属于“1234”,类型为 4 和 5。

最后一条记录属于“4321”的otherid,类型只有4。

我需要选择所有只有类型 4 而不是类型 5 的 otherid。

示例:在该表上进行此选择之后,查询应该只返回记录 3

谢谢

添加1:

请考虑 TYPE 可以是 1 到 20 之间的任何数字。我只需要得到类型 4 而不是类型 5 的 otherid(除了它们可以有任何其他类型)

添加2:

使用 mysql 5.1

4

3 回答 3

1

您可以使用not exists子查询:

select  distinct otherid
from    YourTable as yt1
where   yt1.type = 4
        and not exists
        (
        select  *
        from    YourTable as yt2
        where   yt1.otherid = yt2.otherid
                and yt1.type <> yt2.type  -- use this line for any difference
                and yt2.type = 5          -- or this line to just exclude 5
        )
于 2011-02-20T21:25:38.677 回答
1

这是一种解决方法

SELECT * FROM (
  SELECT GROUP_CONCAT('|',type,'|') type,other_id FROM table GROUP BY otherid
) t WHERE type LIKE '%|4|%' AND type NOT LIKE '%|5|%'
于 2011-02-20T21:31:22.713 回答
0

另一种方法是使用左连接,从中排除同时具有类型 4 和 5 的行:

select a.*
from table1 a
    left join table1 b on b.otherid = a.otherid and b.type = 5
where a.type = 4 and b.id is null
于 2011-02-20T21:50:22.313 回答