17

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

例如。

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|
+----+------+
4

4 回答 4

26

您可以使用 来执行此操作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)
于 2010-04-03T16:17:57.020 回答
14

Aninner join只返回匹配两个表的行:

select distinct p.*
from Parent p
inner join Children c on c.parent = p.id
于 2010-04-03T16:20:53.617 回答
3
Select p.id, p.text
from Parent p
inner join Children c on p.id = c.parent 
group by p.id, p.text
于 2010-04-03T16:20:52.220 回答
1
SELECT p.*
FROM Parent p
WHERE EXISTS (SELECT 'X' FROM Children c WHERE c.parent = p.id);
于 2010-04-03T16:18:52.783 回答