簡體   English   中英

SELECT WHERE conditon = met和condition = not-met,但是有相關的行與condition = met(JOIN?UNION?子查詢?)

[英]SELECT WHERE conditon=met and condition=not-met, but there are related rows with condition=met (JOIN? UNION? Subquery?)

我需要獲得一個滿足某些條件的行的結果集,但還包括不滿足主要條件的行,但這些行鏈接到滿足這些條件的行。 我知道這聽起來可能很復雜而且不清楚,所以我已經將這個任務翻譯成一個簡單的例子。

+--------------------------------+
| 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條件以及其他內容?

另外,如果可以的話,請幫助我改寫問題標題。

做選擇應該讓你思考where 這是表達這種情況的一種典型方式:

select t.*
from t
where t.isRich = 1 or
      t.Id in (select t2.ParentId from t t2 where t2.isRich = 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)

對於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

參見演示http://sqlfiddle.com/#!9/eff447/2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM