Joining Tables Based on Foreign Keys

Posted by maestrojed on Stack Overflow See other posts from Stack Overflow or by maestrojed
Published on 2011-03-01T21:12:51Z Indexed on 2011/03/01 23:24 UTC
Read the original article Hit count: 270

I have a table that has a lot of fields that are foreign keys referencing a related table. I am writing a script in PHP that will do the db queries. When I query this table for its data I need to know the values associated with these keys not the key.

How do most people go about this?

A 101 way to do this would be to query this table for its data including the foreign keys and then query the related tables to get each key's value. This could be a lot of queries (~10).

Question 1: I think I could write 1 query with a bunch of joins. Would that be better?

This approach also requires the querying script to know which table fields are foreign keys. Since I have many tables like this but all with different fields, this means writing nice generic functions is hard. MySQL InnoDB tables allow for foreign constraints. I know the database has these set up correctly.

Question 2: What about the idea of querying the table and identifying what the constraints are and then matching them up using whatever process I decide on from Question 1. I like this idea but never see it being used in code. Makes me think its not a good idea for some reason. I would use something like SHOW CREATE TABLE tbl_name; to find what constraints/relationships exist for that table.

Thank you for any suggestions or advice.

© Stack Overflow or respective owner

Related posts about mysql

Related posts about database