如果相同标识符具有关联的 NULL 值,则 SQL 删除多个值

发布于 2024-09-12 15:56:21 字数 375 浏览 5 评论 0原文

好的,这里是:

我有一个带有 id (可以重复但不能为 NULL )和值(可以重复且为 NULL )的表

id      value
-----   -----
1       red
1       red
1       (null)
2       blue
2       blue
3       (null)

那么如何返回所有具有值的记录的 id 和值,但如果为空值还发现不将其包含在结果集中。

因此,返回结果将是

id      value
-----   -----
2       blue

id 1 和 3 在一个或多个结果中具有 (null) 值

Ok here goes:

I have a table with id ( can be duplicate but not NULL ) and value ( can be duplicate and NULL )

id      value
-----   -----
1       red
1       red
1       (null)
2       blue
2       blue
3       (null)

So how do I return the id's and value's of all the records that have a value, but if a null value is also found don't include it in the result set.

So the return would be

id      value
-----   -----
2       blue

as id 1 and 3 have a value of (null) in one or more of the results

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

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

发布评论

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

评论(2

自由如风 2024-09-19 15:56:21

这是一个典型的“选择不存在的地方”类型的查询,有多种方式来编写答案,例如:

使用 LEFT JOIN / WHERE ... IS NULL:

SELECT DISTINCT T1.id, T1.value
FROM your_table T1
LEFT JOIN your_table T2
ON T1.id = T2.id AND T2.value IS NULL
WHERE T2.id IS NULL

使用 NOT IN:

SELECT DISTINCT id, value
FROM your_table
WHERE id NOT IN
(
    SELECT DISTINCT id
    FROM your_table
    WHERE value IS NULL
)

使用 NOT EXISTS:

SELECT DISTINCT id, value
FROM your_table
WHERE NOT EXISTS
(
    SELECT NULL
    FROM your_table T1
    WHERE your_table.id = T1.id AND T1.value IS NULL
)

It's a typical "select where not exists"-type query with many ways to write the answer, for example:

Using a LEFT JOIN / WHERE ... IS NULL:

SELECT DISTINCT T1.id, T1.value
FROM your_table T1
LEFT JOIN your_table T2
ON T1.id = T2.id AND T2.value IS NULL
WHERE T2.id IS NULL

Using NOT IN:

SELECT DISTINCT id, value
FROM your_table
WHERE id NOT IN
(
    SELECT DISTINCT id
    FROM your_table
    WHERE value IS NULL
)

Using NOT EXISTS:

SELECT DISTINCT id, value
FROM your_table
WHERE NOT EXISTS
(
    SELECT NULL
    FROM your_table T1
    WHERE your_table.id = T1.id AND T1.value IS NULL
)
長街聽風 2024-09-19 15:56:21
select t1.id, t1.value
from MyTable t1
left outer join MyTable t2 on t1.id = t2.id and t2.value is null
where t2.id is null
group by t1.id, t1.value
select t1.id, t1.value
from MyTable t1
left outer join MyTable t2 on t1.id = t2.id and t2.value is null
where t2.id is null
group by t1.id, t1.value
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文