Effective 1 to n linking
I have a table A with fairly large records. Each of those records is related to zero or more records of another table B. I always wondered about the most efficient way to read a record from A and all related records from B out of the Database.
Of course I can use a left join, but then mysql returns n rows, all of which contain the large amount of data stored in the single record from table A.
To get rid of this redundant data, I tried to group the result by the primary key of table A and use GROUP_CONCAT to still retrieve all of the B-records. The query then looks like this:
SELECT A.*, GROUP_CONCAT(B.field1) AS field1, GROUP_CONCAT(B.field2) AS field FROM A LEFT JOIN B ON B.aid = A.id GROUP BY A.id
This works, but has some limitations: I have to split the concatenated B-records on the client side and therefore need a seperator, that must never occur in any of the B-records. The maximum length of GROUP_CONCAT is also limited (I know that you can set this limit). Generally, this doesn't look like a very "clean" solution to me.
The third approach that came to my mind is to just use two queries, one for A and one for B.
Are there better solutions for this quite common problem? Which one would you recommend?
Subject
Written By
Posted
Effective 1 to n linking
June 13, 2009 05:33AM
Sorry, you can't reply to this topic. It has been closed.
Content reproduced on this site is the property of the respective copyright holders.
It is not reviewed in advance by Oracle and does not necessarily represent the opinion
of Oracle or any other party.