これはあなたの質問の最初の部分です。子の部分について詳しく説明していただけますか。猫の親と関係があると思います。
これを試して:
SELECT distinct(p.title)
FROM cats AS c
JOIN cats_products AS cp
ON cp.cat_id = c.id AND c.title = "Electronics"
JOIN products AS p
ON p.id = cp.product_id;
サンプルデータ:
CREATE TABLE cats
(`id` int, `parent` int, `title` varchar(11), `desc` varchar(9))
;
INSERT INTO cats
(`id`, `parent`, `title`, `desc`)
VALUES
(1, 0, 'top', 'top level'),
(2, 1, 'Electronics', ''),
(3, 2, 'Gaming', ''),
(4, 2, 'Computers', ''),
(5, 4, 'Tablets', ''),
(6, 1, 'Food', ''),
(7, 3, 'Xbox', '')
;
CREATE TABLE products
(`id` int, `title` varchar(13), `qty` int)
;
INSERT INTO products
(`id`, `title`, `qty`)
VALUES
(1, 'ToshibaTV', 5),
(2, 'I-PAD2', 9),
(3, 'Laser Pen', 24),
(4, 'Asus Notebook', 5)
;
CREATE TABLE cats_products
(`id` int, `product_id` int, `cat_id` int)
;
INSERT INTO cats_products
(`id`, `product_id`, `cat_id`)
VALUES
(1, 2, 3),
(2, 2, 5),
(3, 1, 2),
(4, 3, 2),
(5, 4, 4)
;
SQL FIDDLE DEMO
編集第2部:
SELECT distinct(v.title) FROM products AS v
JOIN (
SELECT Y.product_id FROM cats_products AS Y
JOIN(
SELECT distinct(z.id) FROM cats AS Z
JOIN
(SELECT c.parent
FROM cats AS c
JOIN cats_products AS cp
ON cp.cat_id = c.id
AND c.title = "Electronics") AS X
ON x.parent = z.parent) AS W
ON W.id = Y.cat_id) AS u
ON u.product_id = v.id
;
サンプルデータ
CREATE TABLE cats
(`id` int, `parent` int, `title` varchar(11), `desc` varchar(9))
;
INSERT INTO cats
(`id`, `parent`, `title`, `desc`)
VALUES
(1, 0, 'top', 'top level'),
(2, 1, 'Electronics', ''),
(3, 2, 'Gaming', ''),
(4, 2, 'Computers', ''),
(5, 4, 'Tablets', ''),
(6, 1, 'Food', ''),
(7, 3, 'Xbox', '')
;
CREATE TABLE products
(`id` int, `title` varchar(13), `qty` int)
;
INSERT INTO products
(`id`, `title`, `qty`)
VALUES
(1, 'ToshibaTV', 5),
(2, 'I-PAD2', 9),
(3, 'Laser Pen', 24),
(4, 'Asus Notebook', 5),
(5, 'French Fries', 50)
;
CREATE TABLE cats_products
(`id` int, `product_id` int, `cat_id` int)
;
INSERT INTO cats_products
(`id`, `product_id`, `cat_id`)
VALUES
(1, 2, 3),
(2, 2, 5),
(3, 1, 2),
(4, 3, 2),
(5, 4, 4),
(5, 5, 6)
;
これはあなたの質問の私の解釈です:すべてのカテゴリには親があり、同じ親を持つ他のすべてのカテゴリを選択したいと考えています。同じ親カテゴリを持つすべての製品をより具体的にします。
SQL FIDDLE DEMO