I trying to fetch data from two related tables using a foreign key and keep the data as separate records / objects.
The best solution I have found so far is using JOINs with column prefixing to differentiate between the two tables.
SELECT
tableA.method AS tableA_method,
tableB.primitiveType AS tableB_primitiveType
FROM tableB
JOIN tableA ON tableB.tableA_id = tableA.id
WHERE tableB.id = ?
This works, but means I have to split the data after the query is completed. Is there a way to perform a single SQL query that returns separate records for each table’s data?
Current result: A single object/RowDataPacket with columns from both tables
[ RowDataPacket { tableA_method: "some value", tableB_primitiveType: "some value }]
Desired result: Two objects, one for each table
[ RowDataPacket { method: "some value" }, RowDataPacket { primitiveType: "some value" }]
or
[ RowDataPacket { tableA: { method: "some value" }, tableB: { primitiveType: "some value }}]
I’ve looked into subqueries, but they involve multiple queries and might not be the most efficient solution.
2
Answers
What you want makes only sense if the two tables have the same column. Let’s say tableA has a column name and tableB as well. You can now JOIN them but then you get 2 columns. If you want to "merge" the result set you can use UNION.
A single SELECT statement is not capable of returning different result sets from different tables. But why should it do that? You can just run 2 different SELECTS.
You could set up a stored procedure to execute your two queries in one go.
Set up:
Then, whenever you want to return your two result sets with a single call – for example for an id of 123, you can use: