views:

38

answers:

1

I have a relation mysql database setup. and I want to pull all the data for one item from the main row and all the relational data (ie multiple associated rows) in one query. What's the easiest/best way to do this aside from a multiple JOIN statement in one query?

The tables and query currently used are below.

Relational data

------------------------------------------------------------------------------------------------------------------------------
| value_id | value_site_id | value_field_set_id | value_field_setting_id | value_parent_id | value_parent_type | value_value |
------------------------------------------------------------------------------------------------------------------------------

Primary Table

-----------------------------------------------------------------------
| item_id | item_site_id | item_country_id | item_category_id | etc etc
-----------------------------------------------------------------------

And the Query is

SELECT fs.field_variable_name, fs.field_type, fv.value_value, fv.value_parent_id
FROM T_field_values AS fv 
    INNER JOIN T_field_settings AS fs ON fv.value_field_setting_id=fs.field_id
WHERE fv.value_parent_type=:type &&
    fv.value_parent_id=:id;
+1  A: 

The best way is to use multiple JOIN clauses, one for each relationship.

Don't fear the JOIN. It's standard practice.

The other way is to use a sub query for each one, but the query optimizer will turn them into JOINs anyway.

The JOIN query will be easier to read.

EDIT

I see, you have some form of EAV tables. Your case is a bit complex, and without the complete structure (T_field_settings is missing) and some sample data, I'm not going to attempt to provide the exact query, but take a look at my previous answer here, on how to use a self join to get results from a EAV table. It should get you going on the right track.

Marcus Adams
I only said not join because it could be up to `n` pieces of data with no limit.
buggedcom
@buggedcom, I expanded my answer because you can use sub queries also. If you provide more details, we can provide examples. It won't be unlimited. You can't have more joins than rows.
Marcus Adams
Question updated.
buggedcom
@Updated answer.
Marcus Adams