I have the following database structure:
`Products`
-------------------------------------
ID | ProductNo
-------------------------------------
1 | 3340
2 | 3450
`ProductVariants`
-------------------------------------
ID | MasterID (ref to `Products`.`ID`) | ProductNo
-------------------------------------
1 | 1 | 3341
2 | 1 | 3342
3 | 2 | 3451
How do I get the Products and their Product Variants with one query?
EDIT:
Desired result:
MasterID | IsMaster | ProductNo | VariantProductNo
1 | 1 | 3340 | null
1 | 0 | 3340 | 3341
1 | 0 | 3340 | 3342
2 | 1 | 3450 | null
2 | 0 | 3450 | 3451
This would do it
Normally done with a single query for efficiency (you could have a query on the Products table, loop round the results of that and for each one do a query on the ProductVariants table, but it would be dog slow).
You could use a LEFT OUTER JOIN instead if you wanted products for which there were no variants
To go with your updated requirements, something like this (not tested so excuse any typos)