If I have a table like this:
TABLEA:
id| object | type
1 | greg | person
2 | mary | person
3 | jared | person
4 | kelly | person
5 | melissa | person
6 | william | person
7 | skiing | hobby
8 | biking | hobby
TABLEB:
id | husband | wife
1 | greg | mary
2 | jared | kelly
3 | william | kelly
TABLEC:
id | female | hobby
1 | mary | skiing
2 | kelly | biking
Is there some way I could get a result table of:
TABLED:
id | a | b | link
1 | 1 | 2 | related
2 | 3 | 4 | related
3 | 6 | 4 | related
4 | 1 | 4 | related
5 | 2 | 7 | likes
6 | 4 | 8 | likes
Using only MySQL query(/ies)?
- Logic would basically start iterating from TABLE B and all rows of table B.
- The third column is
relatedwhen the table being selected isTableB, and islikeswhen the table being processed is TABLE B.
Sample logic would be:
Looking at the first row of TABLEB (husband) greg and wife (mary), it looks up from TABLEA to see that greg is at row 1 (id 1) and mary is at row 2 (id 2) and creates a new TableD with the first row being 1 | 2.
Is there a query that can do some join or something that would be able to do this without having to programmatically iterate through all rows of TABLEB, then all rows of TABLEC to produce the desired TABLED?
You will need to
JOINthe tabletableatwo times with thetableb:husband>objectand another,wife>object.So that you can get the two ids of the husband and wife in the same row.
The same with
Tablecwithtablea. Then useUNION(implicit distinct) orUNION ALLto union the two result sets.Something like:
SQL Fiddle Demo
This will give you:
Note that:
This query will give you only 5 rows, where the expected result set that you are looking for is 6. It is missing the row
4 | 1 | 4 | related, because there is no entry for thosegreg(id 1) andkeyll(id 4) in thetableb. As you explained in your question.The new column
idis auto incremental id, generated from the result set, it is not selected from the tables.If you need to create a brand new table from this select, use the following syntax:
and you will have a new table
tabledhaving the same structure of thisSELECT.Like in this updated fiddle.