我正在尝试找到所有孙子的特定ID,但我似乎无法使我的联接正确。以下代码有效,但我需要从products表中获取与之关联的产品。
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
这是我的架构:
答案 0 :(得分:2)
我认为你正在寻找这个(我已经为“debuggability”添加了类别名称):
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