MYSQL select a value following three relations across tables
I have created a join for an application I am working on.
SELECT community.id,
community.name,
property.type,
property.lowest_price,
property.highest_price,
property.commission_rate,
property.fixed_bonus
FROM community,
property
WHERE community.zip IN ($zips)
AND property.community_id = community.id
I am looking to select an additional value that requires following three relations and am unsure the best way to do that.
The value I want to get is builder_group.name
The community table has community.user_id
which correlates with the builder table builder.user_id
The builder table also has a builder.builder_group_id
which correlates with the builder_group
table's builder_group.id
The builder_group
table finally has the value I want to select builder_group.name
Also, what is the best way to return the count for pagination purposes. Is it best to just do it once initially without returning columns and pass along at the PHP level or can it be ret开发者_如何学编程urned with the SELECT without significant overhead?
If you switch to explicit JOIN conditions, things become clearer:
SELECT community.id, community.name,
property.type, property.lowest_price, property.highest_price, property.commission_rate, property.fixed_bonus,
builder_group.name
FROM community
JOIN property on property.community_id = community.id
JOIN builder on builder.user_id = community.user_id
JOIN builder_group on builder_group.id = builder.builder_group_id
WHERE community.zip IN ($zips)
If you're worried about all those JOINs being slow then review the indexes on the columns involved in the join conditions (yet another reason to use explicit JOINs) and profile the query.
As far as your pagination question goes, You might want to read about the FOUND_ROWS()
function.
SELECT community.id,
community.name,
property.type,
property.lowest_price,
property.highest_price,
property.commission_rate,
property.fixed_bonus,builder_group.name
FROM community
JOIN property ON property.community_id = community.id
JOIN builder ON builder.user_id = community.user_id
JOIN builder_group.id ON builder_group.id = builder.builder_group_id
WHERE community.zip IN ($zips)
精彩评论