2つのテーブルがあります。
親と子の両方の製品名を表示するビューを作成しますが、どちらも同じテーブルから派生しています。
以下は、テーブルの作成例です。
create table plugins_t
(
rid int auto_increment,
product_name varchar(156) not null,
constraint plugins_t_rid_uindex
unique (rid)
);
alter table plugins_t
add primary key (rid);
create table parent_2_childs_t
(
rid int auto_increment,
parent_plugin_id int not null,
child_plugin_id int not null,
constraint parent_2_childs_t_rid_uindex
unique (rid),
constraint parent_2_childs_t_plugins_t_rid_fk
foreign key (parent_plugin_id) references plugins_t (rid),
constraint parent_2_childs_t_plugins_t_rid_fk_2
foreign key (child_plugin_id) references plugins_t (rid)
);
alter table parent_2_childs_t
add primary key (rid);
INSERT INTO plugins_t
(product_name)
values
('product1'),
('product2'),
('product3'),
('product4');
INSERT INTO parent_2_childs_t
(parent_plugin_id, child_plugin_id)
VALUES
(1, 3),
(2, 3),
(2, 4);
INSERT INTO plugins_t
(product_name)
values
('product1'),
('product2'),
('product3'),
('product4');
INSERT INTO parent_2_childs_t
(parent_plugin_id, child_plugin_id)
VALUES
(1, 3),
(2, 3),
(2, 4);
サブクエリを使用して2つの選択を使用しましたが、重複した値を取得しました。
select
pt.product_name as parent_product_name,
c.product_name as child_product_name
from plugins_t as pt
right join parent_2_childs_t p2ct on pt.rid = p2ct.parent_plugin_id
join (
select pt2.product_name from plugins_t as pt2
join parent_2_childs_t p2ct2 on pt2.rid = p2ct2.child_plugin_id
) as c
これは望ましい出力です:
| Parent name | child name |
------------------------------
| product1 | product3 |
| product2 | product3 |
| product2 | product4 |
クエリは機能しました
select parent.product_name as parent_product_name, child.product_name as child_product_name
from plugins_t as parent inner join parent_2_childs_t p2ct on parent.rid = p2ct.parent_plugin_id
inner join plugins_t as child on child.rid = p2ct.child_plugin_id