sql - 在自我引用 table 中获取带或不带 child 的 parentID

sql - get parentID with or without child in self refrenced table

这是我 table 的(活动)内容。 eventID 是 "primary key" 并且 parentID 是 "foreign key" 并引用了 events(eventsID)

自引用 table :

    eventID eventName parentID appFK
    1       evt1      null     2
    2       evt2      1        1
    3       evt3      1        1
    4       evt4      null     3
    5       evt5      8        3
    6       evt6      null     4
    7       evt7      null     1
    8       evt8      null     1

和另一个 table 内容(应用程序)是这样的:

    
    appID appName 
    1     app1      
    2     app2      
    3     app3      
    4     app4

我想获取所有 parents 或不具有给定 appID 的事件 ID。如果 child 具有给定的 appID,我想获取他的 parentID 而不是他自己。所以结果将是这样的,appID = 1 :

    eventID eventName ParentID appFK
    1       evt1      null     2     // parent event who has children with appID = 1
    7       evt7      null     1     // event with no child and appID = 1
    8       evt8      null     1     // parent event with appID = 1 and has a child

我在这里尝试了很多示例并阅读了很多解决方案,但我没有发现这样的问题。你能帮我写正确的 SQL 吗?

谢谢。

试试这个:

SELECT DISTINCT COALESCE(e2.eventID, e1.eventID), 
       COALESCE(e2.eventName, e1.eventName),
       COALESCE(e2.appFK, e1.appFK)
FROM events AS  e1
LEFT JOIN events AS e2 ON e1.parentID = e2.eventID AND e1.appFK = 1
WHERE (e1.appFK = 1 AND e1.parentID IS NULL) OR (e2.eventID IS NOT NULL)

LEFT JOIN 获取 appID = 1 (e1.appFK = 1) 的子项的 parent 记录 (e1.parentID = e2.eventID)。

WHERE 子句选择具有 appID = 1 根记录的根记录,这些根记录与具有 appID = 1 的子项相关(e2.eventID IS NOT NULL).

Demo here