我需要获得满足特定条件的行的结果集,但还包括不符合主要条件但链接到满足它们的行的行。我知道这可能听起来很复杂而且不清楚,所以我将这个任务翻译成一个简单的例子。
+--------------------------------+
| people |
+--------------------------------+
| ID | Name | IsRich | ParentID |
+--------------------------------+
| 100 | John | 1 | NULL |
| 101 | Tom | 0 | NULL |
| 102 | Kate | 0 | 101 |
| 103 | Bob | 0 | 100 |
| 104 | Mike | 1 | 105 |
| 105 | Bill | 0 | NULL |
+--------------------------------+
在这个例子中,我想选择所有富的人和那些不富裕,但有一个富裕的孩子的人:
+---------------------+
| Desired result set |
+---------------------+
| ID | Name | IsRich |
+---------------------+
| 100 | John | 1 | -> because he is rich
| 104 | Mike | 1 | -> because he is rich
| 105 | Bill | 0 | -> because Mike is his child, and Mike is rich
+---------------------+
可以用什么SQL来获取此结果集?
子查询,UNION,JOIN,某种形式的WHERE条件,还有其他什么?
另外,如果可以的话,请帮我改一下问题标题。
答案 0 :(得分:4)
做出选择应该让你想到where
。这是表达这一点的典型方式:
select t.*
from t
where t.isRich = 1 or
t.Id in (select t2.ParentId from t t2 where t2.isRich = 1)
答案 1 :(得分:1)
Gordon Linoff提到的子选择效果很好。但是,如果你想使用连接(例如从孩子那里获取额外的数据),这是另一种可能的解决方案。
SELECT
*
FROM
-- look at all of the rows of people
people parent
-- tack on the child of each row
LEFT JOIN people child ON child.ParentID = parent.ID
WHERE
-- if either the child or the parent are rich, return the row
(child.isRich = 1 || parent.isRich = 1)
答案 2 :(得分:1)
使用UNION也可以。
# SELECT all rich people (parent)
SELECT
people.id
, people.Name
, people.isRich
FROM
people
WHERE
people.isRich = 1
UNION ALL
# SELECT people (parent) with an rich child.
SELECT
parent.ID
, parent.Name
, parent.isRich
FROM
people parent
INNER JOIN
people child
ON
parent.id = child.parentID
WHERE
child.isRich = 1
<强>结果强>
id Name isRich
------ ------ --------
100 John 1
104 Mike 1
105 Bill 0