我在 MYSQL 中有两个表,一个包含客户可以从中选择的选项列表,另一个包含选项的成本。我想要一个返回每个客户选项集成本的 View 。对于我的例子,我将使用购买新车的类比。
客户表
customer - sunroof - mag_wheels - spoiler
--------------------------------------------------
John - true - true - false
Steve - false - true - false
Lucy - false - false - false
选项表
option - price
-----------------
sunroof - 100
mag_wheels - 150
spoiler - 75
期望的结果
customer - cost
-----------------
John - 250
Steve - 150
Lucy - 0
或者这样做,因为我可以轻松地按价格乘以选择,然后按客户分组
customer - option - selected - price
------------------------------------------
John - sunroof - true - 100
John - mag_wheels - true - 150
John - spoiler - false - 75
Steve - sunroof - false - 100
Steve - mag_wheels - true - 150
Steve - spoiler - false - 75
Lucy - sunroof - false - 100
Lucy - mag_wheels - false - 150
Lucy - spoiler - false - 75
我已经为此困惑了几个小时,我什至不知道从哪里开始,连接似乎不可能,因为没有共同的元素可以匹配。我想知道使用 UNION 是否是答案,但我不知道如何将行值与列标题组合起来。
如果有人能指出我正确的方向,我将非常感激,如果您想出一个可以动态选择不同选项的解决方案,那么我将加倍加分,以便我将来可以添加更多选项而无需重写查询。
提前非常感谢。
我希望将所有选项作为单行的原因是我希望使用 Access 制作一个用于选择选项的表单,但我无法弄清楚单个表单如何创建多行。
最佳答案
这是一个糟糕的数据布局。您应该有一个关联表,每个客户和选项占一行。
但是,你可以做到:
select c.customer, sum(o.cost) as cost
from customers c left outer join
options o
on (c.sunroof = true and o.option = 'sunroof' or
c.mag_wheels = true and o.option = 'mag_wheels' or
c.spoiler = true and o.option = 'spoiler'
)
group by c.customer;
编辑:
您不希望所有选项都在一条记录中。相反,您需要一个关联表:
create table customer_options (
customer_optionid unsigned auto_increment,
customer varchar(255) references customer(name),
option varchar(255) references option(option)
);
实际上,所有表都应该有整数主键,并将它们用作外键引用。如果您需要问题输出中的数据,则只需编写一个查询即可以该格式返回它。
关于MYSQL 查询将列名与另一个表中的行匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21176884/