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;
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.
精彩评论