I have two tables that can have multiple records linking to another table, but I don’t want mySQL to combine rows together. Example:
- test_main contains fields mainID, field1.
- test_veg contains a record with a name of a vegetable, linked to the record in test_main with ID=1
- test_fruit contains two records each with a name of a fruit, both linked to the record in test_main with ID=1
In this example there are three records that link to test_main – one test_veg and two test_fruit. I want to get those 3 rows to give a result like:
field1 vegName fruitName
------------------- ------- ---------
stuff in main table cabbage NULL
stuff in main table NULL apple
stuff in main table NULL pear
I would also like records from test_main that don’t have any test_veg or test_fruit records linked to them.
This seems so simple but I can’t get it to work. Any ideas?
If I only had two tables (e.g. test_main and test_veg), a left join would work. With 3 tables, two left joins return only two rows:
SELECT test_main.field1, test_veg.vegName, test_fruit.fruitName
FROM test_main
LEFT JOIN test_veg ON test_veg.mainID = test_main.mainID
LEFT JOIN test_fruit ON test_fruit.mainID = test_main.mainID
WHERE test_main.mainID=1
field1 vegName fruitName
------------------- ------- ---------
stuff in main table cabbage apple
stuff in main table cabbage pear
NB I’m stuck with mySQL3, which means no fancy things like SELECTs within WHEREs, nor UNIONs.
There is a very cool article I read a while back about tricking MySQL3.x into mimicking a
UNION. You need to create a DUMMY table with as many rows as needed for the Unions. So if you have 1 union (which is 2 different select statements), you’d need 2 rows in the dummy table.Try something like this:
Here is the SQL Fiddle to better help you follow along.