我想根據已選擇的行中的值從數據庫中的連接表中選擇行。基本上,如果父級或Granparent行處於活動狀態,則還應在結果中包含子級或孫級行。MySQL:根據已選行中的值選擇行
我試圖使用JOINS
和UNIONS
的不同組合來獲得我想要的結果而沒有成功。
這是我的數據。例如:
表1:目標 (目標可供成員設置爲目標或完成)
id | name | parent
---------------------------
A | Obj A | null
A1 | Obj A1 | A
A2 | Obj A2 | A
A2-1 | Obj A2.1 | A2
B | Obj B | null
B1 | Obj B1 | B
B1-1 | Obj B1.1 | B1
C | Obj C | null
C1 | Obj C1 | C
C1-1 | Obj C1.1 | C1
表2:memberObjectives (目標成員已經完成或設定爲目標)
id | objective | member | status
-----------------------------------
1 | A | 001 | goal
2 | A1 | 001 | complete
3 | C | 001 | goal
期望的結果:加入兩個表,並選擇所有行的狀態是goal
或complete
或當父母或祖父母物鏡具有goal
或complete
狀態。
objective | member | name | status
------------------------------------------
A | 001 | Obj A | goal
A1 | 001 | Obj A1 | complete
A2 | 001 | Obj A2 | null
A2-1 | 001 | Obj A2-1 | null
C | 001 | Obj C | goal
C1 | 001 | Obj C1 | null
C1-1 | 001 | Obj C1.1 | null
A2
和C2
都包括在內,因爲他們的父母A
和C
有goal
和A2-1
和C1-1
一個狀態都包括在內,因爲他們有與goal
狀態祖父母。 B
及其子女和granchild目標不包括在內,因爲memberObjectives
表中的B
的狀態爲complete
或goal
。
我的最新嘗試,我知道甚至沒有接近如下:
SELECT DISTINCT mo.objective, mo.member, o.name, mo.status
FROM objectives AS o
LEFT JOIN (SELECT * FROM memberObjectives
WHERE member = '001') AS mo ON o.id = mo.objective
LEFT JOIN objectives AS o2 ON o2.id = o.parent
LEFT JOIN objectives AS o3 ON o3.id = o2.parent
GROUP BY o.id
謝謝您可以提供任何幫助!
如果你的ID是數字而不是A,A1等,這將是容易的。是你唯一想要的A嗎?或者僅僅是你的榜樣?因爲你可以過濾掉A.問題是祖父母不可能只是加入 –
@JohnRuddell'A's就是這個例子。我可能想要得到所有具有「目標」或「完成」狀態或者具有該狀態的父母或祖父母的「A」和「C」,但沒有任何「B」,因爲該成員沒有完成任何「B」或將其設定爲目標。 –
我現在想知道是否有一種方法來連接表,所以我最終得到了兩個額外的列'parentStatus'和'grandparentStatus',這樣如果這些列或原始狀態列中的任何一個都是'goal'或'complete'包含在結果中。 ('WHERE status ='goal'OR status ='complete'OR parentStatus ='goal'OR parentStatus ='complete'OR grandparentStatus ='goal'OR grandparentStatus ='complete'') –