如何仅在至少有一个子项的情况下选择父行?

发布于 2024-08-27 18:38:02 字数 492 浏览 7 评论 0原文

我有一个简单的一对多关系。我想仅当父级至少有一个子级时才从父级中选择行。因此,如果没有子行,则结果集中不会返回父行。

例如。

Parent:
+--+---------+
|id|   text  |
+--+---------+
| 1|  Blah   |
| 2|  Blah2  |
| 3|  Blah3  |
+--+---------+

Children
+--+------+-------+
|id|parent| other |
+--+------+-------+
| 1|   1  | blah  |
| 2|   1  | blah2 |
| 3|   2  | blah3 |
+--+------+-------+

我希望结果是:

+----+------+
|p.id|p.text|
+----+------+
|  1 | Blah |
|  2 | Blah2|
+----+------+

I have a simple one-to-many relationship. I would like to select rows from the parent only when they have at least one child. So, if there are no children, then the parent row is not returned in the result set.

Eg.

Parent:
+--+---------+
|id|   text  |
+--+---------+
| 1|  Blah   |
| 2|  Blah2  |
| 3|  Blah3  |
+--+---------+

Children
+--+------+-------+
|id|parent| other |
+--+------+-------+
| 1|   1  | blah  |
| 2|   1  | blah2 |
| 3|   2  | blah3 |
+--+------+-------+

I want the results to be:

+----+------+
|p.id|p.text|
+----+------+
|  1 | Blah |
|  2 | Blah2|
+----+------+

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

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

发布评论

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

评论(4

婴鹅 2024-09-03 18:38:02

您可以使用 来执行此操作EXISTS,如下所示:

SELECT *
FROM Parent p
WHERE EXISTS (SELECT 1
              FROM Chilren c
              WHERE c.Parent = p.id)

或者使用 IN 如下所示:

SELECT *
FROM Parent p
WHERE p.id IN (SELECT c.Parent
               FROM Chilren c)

You can do this using an EXISTS, like this:

SELECT *
FROM Parent p
WHERE EXISTS (SELECT 1
              FROM Chilren c
              WHERE c.Parent = p.id)

Or using a IN like this:

SELECT *
FROM Parent p
WHERE p.id IN (SELECT c.Parent
               FROM Chilren c)
黯然#的苍凉 2024-09-03 18:38:02

内连接仅返回与两个表匹配的行:

select distinct p.*
from Parent p
inner join Children c on c.parent = p.id

An inner join only returns rows that match both tables:

select distinct p.*
from Parent p
inner join Children c on c.parent = p.id
蓝海似她心 2024-09-03 18:38:02
Select p.id, p.text
from Parent p
inner join Children c on p.id = c.parent 
group by p.id, p.text
Select p.id, p.text
from Parent p
inner join Children c on p.id = c.parent 
group by p.id, p.text
祁梦 2024-09-03 18:38:02
SELECT p.*
FROM Parent p
WHERE EXISTS (SELECT 'X' FROM Children c WHERE c.parent = p.id);
SELECT p.*
FROM Parent p
WHERE EXISTS (SELECT 'X' FROM Children c WHERE c.parent = p.id);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文