Tod*_*ddN 4 php mysql union select
我有3张桌子.寻找一种PRICE使用三个不同的表找到字段差异的好方法,然后显示前3个最大的负差异.我想首先找到最好的MySQL查询使用,并找到在php中显示它的最佳方法.
MAINTABLE:
COMPANY | MODEL | PRICE
Main Company | ProductA | 100.00
Main Company | ProductB | 50.00
Main Company | ProductC | 25.00
Main Company | ProductD | 300.00
Run Code Online (Sandbox Code Playgroud)
COMPTABLE1:
COMPANY | MODEL | PRICE
Competitor1 | ProductA | 100.00 //0
Competitor1 | ProductB | 55.00 //5
Competitor1 | ProductC | 50.00 //25
Competitor1 | ProductD | 200.00 //-100
Run Code Online (Sandbox Code Playgroud)
COMPTABLE2:
COMPANY | MODEL | PRICE
Competitor2 | ProductA | 99.00 //-1
Competitor2 | ProductB | 44.00 //-6
Competitor2 | ProductC | 20.00 //-5
Competitor2 | ProductD | 100.00 //-200
Run Code Online (Sandbox Code Playgroud)
因此,我希望在页面中显示的PRICE中最大的负面差异是:
IDEA:我不这么familar,但我可以用一个.. UNION SELECT在三个表WHERE MODEL=XXX.我可能会遍历每一个收集数据,进行数学运算并吐出信息的人.唯一的问题是,我不知道如何将EACH变量存储为每个表的自己的价格.此外,我认为它会显示所有差异,除非在进行数学运算后存储每个变量的方法,然后显示前3个差异.
任何想要或最好的解决此查询的建议将不胜感激.(注意:不,我不能将它们全部放在一个表中= p)
在PHP方面无法帮助,但是这个查询应该可以满足您的需求.你必须做一个工会才能获得所有合格的结果.这将使所有列都可用并预先计算,以便以您需要的任何方式将其放入简单的网格列表中.由于计算是竞争对手与主要公司,因此通过自然顺序的PriceDifference将首先具有最大负面,然后变为正面.因此,LIMIT命令将在订购后应用,只返回3条记录.
select
MT.Model,
MT.Company as MainCompany,
MT.Price as MainPrice,
CT1.Company as Competitor,
CT1.Price as CompPrice,
CT1.Price - MT.Price as PriceDifference
from
MainTable MT
JOIN CompTable1 CT1
on MT.Model = CT1.Model
UNION
select
MT.Model,
MT.Company as MainCompany,
MT.Price as MainPrice,
CT2.Company as Competitor,
CT2.Price as CompPrice,
CT2.Price - MT.Price as PriceDifference
from
MainTable MT
JOIN CompTable2 CT2
on MT.Model = CT2.Model
order by
PriceDifference
limit 3
Run Code Online (Sandbox Code Playgroud)
建议......你的表格结构的方式从长远来看真的很糟糕.您应该尝试规范化数据以获得更佳的性能.如果您有100个竞争对手会发生什么.你到处都有重复.也改变模型名称.以下是我将如何重组表格...而不是明确的数据类型,但在概念上
COMPANY
CompanyID auto-increment
CompanyName character
PRODUCT
ProductID auto-increment
ProductModel character
VendorPricing
VPriceID auto-increment
CompanyID (ID pointing to company table -- to get name when needed)
ProductID (ID pointing to product table -- to get model name too)
Price actual price for this particular company and product
Run Code Online (Sandbox Code Playgroud)
然后,使用适当的索引,如果您想要从一个供应商到另一个供应商的定价,以及任何型号,您的查询将来可能更容易扩展...类似于
select
VP1.CompanyID,
C1.CompanyName as MainCompany,
C2.CompanyName as Competitor,
P1.ProductModel,
VP1.Price as MainPrice,
VP2.Price as CompetitorPrice,
VP2.Price - VP1.Price as PriceDifference
from
VendorPricing VP1
JOIN Company C1
on VP1.CompanyID = C1.CompanyID
JOIN Product P1
on VP1.ProductID = P1.ProductID
JOIN VendorPricing VP2
on VP1.ProductID = VP2.ProductID
AND NOT VP1.CompanyID = VP2.CompanyID
JOIN Company C2
on VP2.CompanyID = C2.CompanyID
where
VP1.CompanyID = TheOneCompanyYouAreInterestedIn
order by
PriceDifference
limit 3
Run Code Online (Sandbox Code Playgroud)
所以现在,如果您有2个,5个,10个或100个竞争对手,则查询完全相同.