仅选择必须满足两个条件的记录

发布于 2024-10-18 10:37:43 字数 412 浏览 1 评论 0原文

我有这个表:

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

正如你所看到的,有3条记录,其中2条属于otherid“1234”,类型为4和5。

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

我需要选择仅包含类型 4 而未包含类型 5 的所有 otherid。

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

谢谢

add1:

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

add2:

using mysql 5.1

I have this table:

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

As you can see there are 3 records, 2 of them belongs to otherid "1234" and got type of 4 and 5.

Last record belongs to otherid of "4321" and has only a type of 4.

I need to select all otherid that got only the type 4 and not the type5.

Example: after this select on that table the query shuould return only the record 3

Thanks

add1:

Please consider the TYPE can be any number from 1 up to 20.
I only need otherid that got type 4 but not type 5 ( except than that they can have any other type )

add2:

using mysql 5.1

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

简美 2024-10-25 10:37:43

这是一种解决方法

SELECT * FROM (
  SELECT GROUP_CONCAT('|',type,'|') type,other_id FROM table GROUP BY otherid
) t WHERE type LIKE '%|4|%' AND type NOT LIKE '%|5|%'

This is kind of a workaround

SELECT * FROM (
  SELECT GROUP_CONCAT('|',type,'|') type,other_id FROM table GROUP BY otherid
) t WHERE type LIKE '%|4|%' AND type NOT LIKE '%|5|%'
相对绾红妆 2024-10-25 10:37:43

您可以使用 not contains 子查询:

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
        )

You could use a not exists subquery:

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
        )
才能让你更想念 2024-10-25 10:37:43

另一种方法是使用左联接,从中排除同时具有类型 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

Another way is by using a left join from where you exclude rows that have both type 4 and 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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文