我試圖找到一個特定的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
這裏是我的架構:
有什麼錯誤?有些sql引擎不喜歡select *,當你有連接和類似的語法時。應該選擇p。*,pc。* – chris
模式與問題的其餘部分不匹配。對於初學者來說,我甚至都不會在任何地方看到「父」字段。 –
@TomvanderWoerdt - 真實的故事,我有錯誤的形象...我道歉;) – Mike