Combining two tables with fkey relationship - mysql

I am trying to join two tables which are only related on another table (3rd table) and the identity of the two tables are foreign key of the 3rd table. Please refer to the image below so that I can fully describe what I am trying to achieve.
Relationship specs:
Actual.Id = Actual x Budget.Id
Budget.Id = Actual x Budget.Id
Budget.DateField = Actuals x Budget.DateField
And the last relationship: They are assigned as same data on Actual x
Budget.ColA
Is this achievable or should I change my database schema?

For your ActualXBudget table, don't use a single field for ID's from BOTH actual and budget. Use two columns, one for budgetID and one for ActualID. That way, a single row from ActualXBudget will be linked to both budget and Actual.
With your design, the DB has no idea that Budget ID 4 = Actual ID 1.
With Actual ID and Budget ID in the ActualXBudget Table, you can do simple joins to both tables and pull out attached records, like
SELECT Actual.ColA,Actual.ColB,Budget.ColB,Budget.ColC FROM
(Actual INNER JOIN ActualXBudget ON Actual.ID = ActualXBudget.ActualID)
INNER JOIN Budget ON Budget.ID = ActualXBudget.BudgetID
Edit: With your setup you could do
SELECT Actual.ColA,Actual.ColB,Budget.ColB,Budget.ColC FROM
(Actual INNER JOIN ActualXBudget ON Actual.ID = ActualXBudget.ID )
INNER JOIN Budget ON Budget.DateField = ActualXBudget.DateField
but don't do that.

Related

MS Access Query Results - Relationship Extension

I have 4 tables: A, B, C and a linking table. I would like to know if it is possible to retrieve records from C by setting criteria in A, where there is a record in the linking table which links A and B, and a separate record in the linking table for B and C.
Here's a simplified image of the relationships:
I have tried setting up a query showing relevant fields from A, B and C, with criteria set in A. The linking table is present in the query. Running the query only returns the linked records from B. Is there something I should be putting in the criteria in the linked field of C? (I am doing this in design view for the query - my knowledge SQL is limited.)
.
SQL from Access:
SELECT Fruits.Fruit, Colour.Colour, Pests.Pest
FROM Pests RIGHT JOIN (Fruits RIGHT JOIN (Colour RIGHT JOIN [Linking Table] ON Colour.ID = [Linking Table].Colour) ON Fruits.ID = [Linking Table].Fruit) ON Pests.ID = [Linking Table].Pest
WHERE (((Pests.Pest)="Fly"));
Input: Fly
Output: Apple
Desired Output: Apple and Red
The linking table has a record linking the ID of fruit to pest, and a separate record linking the ID of fruit to colour.
Any assistance is greatly appreciated.
You're using your linking table for 2 kinds of links. This is a bad practice (normalization dictates that all columns in a table should be related, and the column pest has nothing to do with the column colour). Using one table to link color to fruit, and one to link pests to fruit would be a better plan.
You can still use this if you want to, but you will have to join in Linking Table twice (once for the fruit - pests relationship, once for the fruits - color relationship)
Try the following query:
SELECT Fruits.Fruit, Colour.Colour, Pests.Pest
FROM Pests
INNER JOIN [Linking Table] AS LT1 ON Pests.ID = LT1.Pest
INNER JOIN Fruits ON LT1.Fruit = Fruits.ID
INNER JOIN [Linking Table] AS LT2 ON Fruits.ID = LT2.Fruit
INNER JOIN Colour ON LT2.Colour = Colour.ID
This query goes from Pest to Linking table to Fruits then to a second instance of Linking table and then to Colour

Big Query SQL. Combining tables with the same columns (No PK)

I'm trying to combine 3+ NOAA GSOD data tables to get the data together in one super table. The I am attempting to JOIN the stations table onto the resultant data and then filter by country.
I've been able to do this for just one table but not for more. Below is my attempt at modifying the code to achieve this. I tried several different modifications with no success :(
SELECT * FROM [bigquery-public-data:noaa_gsod.gsod2016] AS gsod2016,
[bigquery-public-data:noaa_gsod.gsod2015] AS gsod2015 JOIN [bigquery-public-
data:noaa_gsod.stations] AS stations ON gsod2016.stn = stations.USAF AND
gsod2015.stn = stations.USAF WHERE stations.country = "CB"
NOAA GSOD bigquery data:
https://bigquery.cloud.google.com/table/bigquery-public-data:noaa_gsod.gsod2016
Use 1 standard inner join or , (preferably inner join syntax) and ensure the tables are in the correct order, you can't join on a table unless its' been defined above the ON.
SELECT *
FROM [bigquery-public-data:noaa_gsod.stations] AS stations
INNER JOIN [bigquery-public-data:noaa_gsod.gsod2016] AS gsod2016
ON gsod2016.stn = stations.USAF
INNER JOIN [bigquery-public-data:noaa_gsod.gsod2015] AS gsod2015
ON gsod2015.stn = stations.USAF
WHERE stations.country = "CB"
Now all this said did you really mean a join or did you want to UNION ALL
the data and add a year

MySql - Combine data from three tables into one table

I have 3 tables for data of divisions, districts and police_stations table. The table data are dependent like
divisions
- districts
-- police_stations
Table format are
divisions
id
name
districts
id
division_id
name
police_stations
id
division_id
district_id
name
Can I design just one table with all of my tables data with current table dependency? If I can, how will be the traversing process?
To group multiple tables together, you should use JOINS. This is a better database practice than creating new tables.
The INNER JOIN keyword selects all rows from both tables as long as there is a match between the columns in both tables.
SELECT *
FROM divisions divis
INNER JOIN districts dis
ON dis.division_id = divis.id
INNER JOIN police_stations pol
ON pol.district_id = dis.id
Note: Apparently the DIV keyword is reserved in mysql, so you you have to use something else to identify divisions.
If you insist on creating a new table with this data, you can use the CREATE TABLE AS recipe.
In order to do this though, we need to modify our original schema. New tables cannot have duplicate names, so we have to change the original tables to all have unique columns.
For example name becomes district_name.
CREATE TABLE combined AS (
SELECT divis.id, divis.division_name, dis.district_name, pol.police_name
FROM divisions divis
LEFT JOIN districts dis
ON divis.id = dis.division_id
LEFT JOIN police_stations pol
ON pol.district_id = dis.id
);
Here is a fiddle to demonstrate it
http://sqlfiddle.com/#!9/7ec3b/1/0
This is really bad database design though. My first solution is recommended
Using a single table: There would be an id for uniquely identifying each row; it would be the PRIMARY KEY. There would be a parent_id to say which other row is its 'parent' (division is parent of district, etc).
The JOIN becomes a self join.
SELECT ...
FROM tbl AS division
JOIN tbl AS district ON division.id = district.parent_id
JOIN tbl AS station ON district.id = station.parent_id
WHERE ...
Be sure to 'qualify' each field in the SELECT and WHERE with the appropriate 'alias'; example: division.name.
This design pattern works for most 'hierarchical' structures of arbitrary depth. Yours is exactly 3 levels deep, so it is somewhat simpler.
Note that the parent_id would be 0 for any "district" rows. And it would be useful to have INDEX(parent_id).
Hopefully it solves your problem
SELECT * from divisions d
join police_stations ps on d.id=ps.division_id
join districts dist on ps.district_id =dist.id;

MySQL merge 2 tables with same Id values

I have a MySQL db that has 2 tables that have related information that I need to merge to 1 table.
Gallery has an itemid that relates to rbitems Id. Both tables gallery and rbitems have different column names but both have unique data. I want to merge the two tables based on the Id and itemid columns.
So how do I merge 2 different tables into 1 based on 1 column having unique values. I'd like to just append the other tables to the merge.
You can use JOIN to solve your problem.
SELECT a.*, b.*
FROM galley a INNER JOIN rbitems b
on a.itemid = b.id
CREATE TABLE new_table
AS (SELECT g.itemid, g.a, g.b, g.c, r.x, r.y, r.z
FROM gallery g INNER JOIN rbitems r
ON g.itemid = r.id
);
You may wish to add "AS name" to the members of the select clause.
If you have elements of the original tables that are not represented in the other table you should look into RIGHT, LEFT, or OUTER JOIN instead of INNER.
This assumes that the itemid and id columns are unique--a given itemid/id does not exist multiple times in the same table.

MySQL Join with many (fields) to one (secondary table) relationship

I have a query I need to perform on a table that is roughly 1M records. I am trying to reduce the churn, but unfortunately there is a UNION involved (after i figure this join out), so that may be a question for another day.
The records and data I need to get reference 3 fields in a table that need each pull a description from another table and return it in the same record, but when i do the Inner join i was thinking, it either returns only 1 field fromt he other table, or multiple records from he original table.
Here are some screen shots of the tables and their relationship:
Primary table containing records (1 each) with the physician record I want to pull, including up to 3 codes that can be listed in the "taxonomy" table.
Secondary table containing records (1 each) with the "Practice" field I want to pull.
A Quick glance of the relationship i'm talking about
I presume that if perform an inner join matching the 3 fields in the physicians table, that it will have to iterate that table multiple times to pull each taxonomy code .. but I still can't even figure the syntax to easily pull all of these codes instead of just 1 of them.
i've tried this:
SELECT
taxonomy_codes.specialization,
physicians.provider_last_name,
physicians.provider_first_name,
physicians.provider_dba_name,
physicians.legal_biz_name,
physicians.biz_practice_city
FROM
taxonomy_codes
INNER JOIN physicians ON physicians.provider_taxonomy_code_1 = taxonomy_codes.taxonomy_codes OR physicians.provider_taxonomy_code_2 = taxonomy_codes.taxonomy_codes OR physicians.provider_taxonomy_code_3 = taxonomy_codes.taxonomy_codes
First, the query churns a lot and it only returns one taxonomy specialty result which I presume is because of the OR in the join statement. Any help would be greatly appreciated.
Thank you,
Silver Tiger
You have to join the taxonomy_codes table multiple times:
SELECT p.provider_last_name, p...., t1.specialization as specialization1, t2.specialization as specialization2, t3.specialization as specialization3
FROM physicians p
LEFT JOIN taxonomy_codes t1 ON t1.taxonomy_codes = provider_taxonomy_code_1
LEFT JOIN taxonomy_codes t2 ON t2.taxonomy_codes = provider_taxonomy_code_2
LEFT JOIN taxonomy_codes t3 ON t3.taxonomy_codes = provider_taxonomy_code_3