これは私が考えた設計であり、スキーマを見ない前提です。私のコメントが明確になることを願っています。これが必要なものと異なる場合は、お知らせください。お力になれて、嬉しいです。:)
参照
オプション表:
ID NAME ATTRIBUTE COST
1 headboard S 55.5
2 headboard L 65.2
3 headboard M 60.3
4 colour_change (null) 20.3
5 polishing (null) 70.2
製品表:
ID NAME PCOST
1001 chair 50
1002 bed1 1200
1003 table 200
1004 cupboard 2000
1005 bed2 1000
カスタム テーブル:
ID PID OID CID
1 1002 3 (null)
2 1002 4 2
3 1003 5 (null)
4 1001 4 1
5 1004 5 (null)
クエリ 1 を使用して、製品ごとのカスタマイズに使用されるオプションの合計を取得します。
select c.pid, sum(o.cost)
from custom c
left join options o
on c.oid = o.id
group by c.pid
;
結果 1:
PID SUM(O.COST)
1001 20.3
1002 80.6
1003 70.2
1004 70.2
クエリ 2 : オプション コスト、製品コストの製品別内訳
-- prod cost, option cost by options and prod
select x.pid, p.name, p.pcost, x.optCost,
x.optChoices
from prod p
right join (
select c.pid, sum(o.cost) as optCost,
group_concat(o.name, ' ') optChoices
from custom c
left join options o
on c.oid = o.id
group by c.pid) as x
on x.pid = p.id
;
結果 2:
PID NAME PCOST OPTCOST OPTCHOICES
1001 chair 50 20.3 colour_change
1002 bed1 1200 80.6 headboard ,colour_change
1003 table 200 70.2 polishing
1004 cupboard 2000 70.2 polishing
クエリ 3: 最終回答
-- total cost
select x.pid, p.name, x.optChoices,
(p.pcost + x.optCost) totalCost
from prod p
right join (
select c.pid, sum(o.cost) as optCost,
group_concat(o.name, ' ') optChoices
from custom c
left join options o
on c.oid = o.id
group by c.pid) as x
on x.pid = p.id
;
結果 3:
PID NAME OPTCHOICES TOTALCOST
1001 chair colour_change 70.3
1002 bed1 headboard ,colour_change 1280.6
1003 table polishing 270.2
1004 cupboard polishing 2070.2