2013-01-22 144 views
3

我試圖找到一個特定的ID的所有孫子,但我似乎無法讓我的連接正確。下面的代碼有效,但是我需要從產品表中獲取與其關聯的產品。如何找到孫子女?

SELECT b.category_id, b.category_name, b.parent, a.parent 
FROM categories AS a, categories AS b 
WHERE a.category_id = b.parent AND a.parent = 119 

當我嘗試加入產品表我不斷收到一個錯誤:

SELECT * 
FROM products p 
INNER JOIN products_categories pc 
ON p.product_id = pc.product_id 
INNER JOIN (
     SELECT b.category_id, b.category_name, b.parent, a.parent 
     FROM categories AS a, categories AS b 
     WHERE a.category_id = b.parent AND a.parent = 119 
    )x 

我期望的結果將是有以下幾點:(注:看看我的SQL小提琴看模式在代碼視圖)

(76, 'BR134', 'LEA530664', 'ITEM1234', 1499.99, 'yes', 'This is a nice gun'), 
(77, 'mZCXGT', 'LEA471061', 'qwer345', 89.99, 'yes', 'Testing!'), 
(78, 'ert', 'LEA023991', 'asdf34', 129.99, 'yes', 'Another test to get this right!'), 
(79, 'model test', 'LEA355935', 'item test', 119.99, 'yes', 'This is another test dammit!'), 
(80, 'CZV1354', 'LEA741837', 'LI-1234', 1299.99, 'yes', 'This is a hipoint weapon!'), 
(81, 'PINK12G', 'LEA008558', 'PINK-SHG', 89.99, 'yes', 'YEP! This is pink!'), 
(82, 'BOWTECH', 'LEA762521', 'asdf', 899.99, 'yes', 'This is a test!'), 
(83, 'LX32', 'LEA346903', 'MADEUP', 1499.99, 'yes', 'This is Carters gun.'); 

SQL小提琴:

http://sqlfiddle.com/#!2/dd66c/2

這裏是我的架構: enter image description here

+0

有什麼錯誤?有些sql引擎不喜歡select *,當你有連接和類似的語法時。應該選擇p。*,pc。* – chris

+0

模式與問題的其餘部分不匹配。對於初學者來說,我甚至都不會在任何地方看到「父」字段。 –

+0

@TomvanderWoerdt - 真實的故事,我有錯誤的形象...我道歉;) – Mike

回答

2

我認爲你正在尋找這個(我已經添加了「可調試」類別名稱):

SELECT 
    p.product_id 
, p.model 
, p.sku 
, p.item_number 
, p.msrp 
, p.availability 
, p.description 
, grand_child.category_name AS grand_child_category 
, child.category_name AS child_category 
, parent.category_name AS parent_category 
FROM categories parent 
INNER JOIN categories child 
ON parent.category_id = child.parent 
INNER JOIN categories grand_child 
ON child.category_id = grand_child.parent 
INNER JOIN products_categories pc 
ON grand_child.category_id = pc.category_id 
INNER JOIN products p 
ON p.product_id = pc.product_id 
WHERE parent.category_id = 119 
+0

嗯,非常好。這工作很好。謝謝你,很好的工作;) – Mike

+0

Aaha,現在刪除我的答案,我看到預期的結果是什麼。 +1 – RThomas

相關問題