Skip to content
Advertisement

Is there a better way I can structure my tables, do a 4 table join, or will I have to perform multiple queries?

What is the correct way to perform this GET request? I currently have 4 tables:

events, event_comments, event_photos, event_users_going

The last 3 tables, event_comments, event_photos, and event_users_going all have a foreign key that uses events table’s primary key.

What I am unsure about is, would I have to do a JOIN on all 4 tables or 4 individual queries? Because, each query on each table returns a different number of rows.

For example the first query would be on events:

this returns 1 row.

The 2nd query:

this returns 12 rows

3rd Query:

this returns 20 rows

4th Query:

this returns 30 rows

Advertisement

Answer

It depends on what is receiving the results. If it can process JSON and the overhead of doing so isn’t a deal-breaker, you can do the following to include related rows as JSON arrays:

Sample output:

When returning JSON, you can take it a step further and build a result with a single column:

Sample output:

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