Skip to content
Advertisement

mysql – fetch related rows from multiple tables without all combinations

Let’s say I have a primary table record, and it has 2 related tables fields and comments.

I would like to run one query that fetches a set of records AND fetches all the related fields for that record, AND fetches all the comments related to that record.

If I do left joins to ensure I get the records, I would use:

The problem is, I get back n * m rows for each record, where n is the number of fields, and m is the number of comments. I want to get back n + m rows (what makes sense is that the fields columns are all null while returning the comments, and the comments columns are all null while returning the fields). Is there a way to make this work aside from inserting a dummy comment and dummy field to join with? I would very much prefer not to have to perform an extra query for each record.

I suppose this is not mysql specific, but that’s what I’m using for my application.

Advertisement

Answer

I get back n * m rows for each record, where n is the number of fields, and m is the number of comments. I want to get back n + m rows

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement