2011-11-12 141 views
0

我正在嘗試記住SQL解決方案針對此類問題的用途。比方說,我有如下表:集合的交集

tagged_nodes

  1. nid - 節點ID。外鍵。
  2. tid - Tag id。外鍵。
  3. tnid - 主鍵(與問題無關)。

nodes

  1. nid - 節點ID。首要的關鍵。
  2. ... - 其他列無關。

假設我有一組標記ID(tid),我想返回一組關聯節點(相交)。我該怎麼做呢?

回答

-1

所以這裏就是我想出了:

$this->Sql = 'SELECT DISTINCT * FROM `nodes` `n` 
    JOIN `tagged_nodes` `t` ON t.nid=n.nid'; 

$i=0; 
foreach($tagids as $tagid) { 
    $t = 't' . $i++; 
    $this->Sql .= ' INNER JOIN `tagged_nodes` `'.$t.'` ON ' 
     .$t'.tid=t.tid WHERE '.$t.'.tid='.$tagid; 
} 

這是在PHP,因爲我需要它是動態的,但它主要是以下,如果我需要,也就是說,只有2標籤(animals,pets)。

SELECT * FROM nodes n JOIN tagged_nodes t ON t.nid=n.nid 
INNER JOIN tagged_nodes t1 ON t1.tid=t.tid WHERE t1.tid='animals' 
INNER JOIN tagged_nodes t2 ON t2.tid=t.tid WHERE t2.tid='pets' 

我在正確的軌道上嗎?

4
SELECT nodes.* FROM nodes       /* Load node info */ 
JOIN tagged_nodes ON tagged_nodes.nid = nodes.nid /* Match node-tag rows with node rows */ 
WHERE tagged_nodes.tid IN (1, 2, 3)     /* Filter using tag relationship */ 
+0

啊,謝謝。看起來像一個簡單的問題。 – Hamster

+0

當然,很高興幫助! –

+0

@Hamster,你確定你想要這個嗎?漢斯的答案不會被稱爲交集。 –