Question

I'm working with a database that has 2 tables for each company with 4 companies (8 total DBs for thisquery) and for reasons outside of my control that can't be changed. This is also an sqlite DB.

My app currently has to do 8 round trips to get all the data. I want to consolidate that down to one table view query but I can't figure out how to combined the data in a way that would make it work. Here is an example of the tables.

Table 1 (Type A)

name    zone
ABCD    ABC1
DBAA    CBA1

Table 2 (Type A)

name   zone
ABCD   1234
DBAA   4321

Table 1 (Type B)

zone   weight   rate  
ABC1      1     0.50  
CBA1      2     0.88

Table 2 (Type B)

zone   weight   rate
1234      1     0.52
4321      2     0.80

Finally I want the view to look like this:

name   weight   Table 1 rate  Table 2 rate
CABA      1         0.52          0.50
AEAS      2         0.80          0.88

I tried this for my SQL statement:

SELECT 1A.name, 1B.weight, 1B.rate as A from 1A, 1B WHERE 1A.zone = 1B.zone
UNION ALL
SELECT 2A.name, 2B.weight, 2B.rate as B from 2A, 2B WHERE 2A.zone = 2B.zone

I have also tried a couple joins statements after reading unions must have matching column counts but I can't seem to hit the right query. Any ideas what I'm doing wrong or how I can achieve this with a query?

Any help is greatly appreciated!

Updated with Fiddle example here: http://sqlfiddle.com/#!5/37c19/3/0

Was it helpful?

Solution

Here is a query that will produce something similar to your example:

SELECT 
  ZonesOne.name
  , RatesOne.weight
  , RatesOne.rate as Table1Rate
  , RatesTwo.Rate AS Table2Rate

FROM ZonesOne, RatesOne, RatesTwo 

WHERE 
  RatesOne.zone = ZonesOne.zone
  AND RatesOne.Weight = RatesTwo.weight

UNION ALL

SELECT 
  ZonesTwo.name
  , RatesOne.weight
  , RatesOne.rate as Table1Rate
  , RatesTwo.Rate AS Table2Rate

FROM ZonesTwo, RatesOne, RatesTwo     

WHERE 
  RatesOne.zone = ZonesTwo.zone
  AND RatesOne.Weight = RatesTwo.weight

However, your Table 1 Rate and Table 2 Rate seem to be switched around. Also, your data from ZonesTwo has two entries for "DBAA".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top