I have 3 tables. Looking for a good way to find the difference in field PRICE using three different tables, then displaying the top 3 largest negative differences. I want to first find the best MySQL query to use, and also find the best way to display it all in 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
COMPTABLE1:
COMPANY | MODEL | PRICE
Competitor1 | ProductA | 100.00 //0
Competitor1 | ProductB | 55.00 //5
Competitor1 | ProductC | 50.00 //25
Competitor1 | ProductD | 200.00 //-100
COMPTABLE2:
COMPANY | MODEL | PRICE
Competitor2 | ProductA | 99.00 //-1
Competitor2 | ProductB | 44.00 //-6
Competitor2 | ProductC | 20.00 //-5
Competitor2 | ProductD | 100.00 //-200
So the largest negative differences in PRICE which I want displayed in my page are:
- Competitor2 ProductD -200 difference from Main Company ProductD
- Competitor1 ProductD -100 difference from Main Company ProductD
- Competitor2 ProductB -6 difference from Main Company ProductB
IDEA: I am not so familar with it, but I could use a ..UNION SELECT on the three tables WHERE MODEL=XXX. I could possibly loop through each one gathering the data, doing the math and spitting out the info. Only problem is, is that I don’t know how to store EACH variable as their own price for each of the tables. Also, I think it would display ALL differences unless there is a way to store each variable after doing the math, then displaying the top 3 differences.
Any ideas or suggestions to best tackle this query would be appreciated. (Note: No I cannot put them all in one table =p )
Can’t help on the PHP side, but this query should get you what you need. You’ll have to do a union to get all the qualified results. This will have all columns available and pre-calculated for you to put into a simple grid listing in whatever fashion you need. Since the calculations are competitor vs main company, the PriceDifference via natural order by will have largest negative first, then go positive. So, the LIMIT command will be applied after the ordering and just send back 3 records.
Suggestion… The way you have your tables structured is really bad for the long haul. You should try to normalize you data for more optimal performance. What happens if you have 100 competitors. You have duplication all over the place. Change a model name too. Here is how I would restructure the tables… not explicit data typing, but conceptually
Then, with appropriate indexes, if you wanted to get pricing from one vendor to another, and whatever model, your query could be easier to expand in the future… something like
So now, if you had 2, 5, 10 or 100 competitors, the query is exactly the same.