簡體   English   中英

根據聯接優先級列的最低值選擇不同的標識行

[英]Selecting distinct identity rows based on the lowest value of a joined priority column

簡化的表結構,所有INT列以及標識列之外的沒有PK:

節點(n)表: id

屬性(a)表: idnode_idtype_id

類型(t)表: idpriority

我正在嘗試選擇一組屬性,每個屬性對於其各自的節點具有最低的type.priority。 雖然每個node_id有多個屬性,但我只想選擇具有最低優先級值的屬性:

a1 n1 t1 p0 *
a2 n1 t2 p1 
a3 n2 t2 p1 *
a4 n2 t3 p2  

這是我正在處理的基本查詢,此時我也陷入困境:

   SELECT * 
     FROM a 
LEFT JOIN t ON a.type_id = t.id 
 GROUP BY node_id

我的第一個想法是使用聚合MIN,但是我遇到了將node_id的最低優先級與正確屬性相匹配的問題。

使用tie-breaker查詢(未測試):

SELECT      n.*, a.*
FROM        Nodes n
LEFT JOIN   Attributes a
        ON  a.id = (SELECT      x.id --//TOP 1 x.id
                    FROM        Attributes x
                    INNER JOIN  Type t
                            ON  x.type_id = t.id
                    WHERE       x.node_id = n.id
                    ORDER BY    t.priority ASC,
                                --//just in case there are 2 attributes 
                                --//with the same priority, order also on x.id
                                x.id ASC
                    LIMIT 1
                    )

這個問題是“每組最大n”問題的變體,但是你要找的是最小的而不是最大的,你的標准是在查找表( Type )而不是主表( Attributes )中。

因此,您需要來自Attributes的行( a1 ),以使具有相同node_id其他行與較低優先級相關聯。

SELECT a1.*
FROM Attributes a1 INNER JOIN Type t1 ON (a1.type_id = t1.id)
LEFT OUTER JOIN (
  (Attributes a2 INNER JOIN Type t2 ON (a2.type_id = t2.id))
  ON (a1.node_id = a2.node_id AND t1.priority > t2.priority)
WHERE a2.node_id IS NULL;

請注意,這可能會導致聯系。 如果兩個屬性引用具有相同優先級的類型,則您尚未描述如何解析關系。 換句話說,在以下示例中,應選擇哪些屬性?

a1 n1 t1 p0 
a2 n1 t1 p0 
a3 n2 t2 p1 
a4 n2 t3 p1 

PS:我希望你不介意我在你的問題中添加了“最大n組”標簽。 點擊該標簽可以查看我已經標記過類似的其他問題。

暫無
暫無

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

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