开发者

Avoid multiple LEFT JOIN

I开发者_开发问答s there a way to avoid adding a second LEFT JOIN for the table "social_mcouple" to query where social_members.m_id = social_mcouple.c_id below?

$res = @mysql_query("SELECT *, DATE_FORMAT(m_lld,'%m/%d/%y') AS m_lld_formatted FROM social_members 
        LEFT JOIN social_member_types ON t_id=m_type WHERE m_user='".$en['user']."'");


If there will always be a social_mcouple that corresponds to social_members, or you're only interested in rows where there is a correspondence then you may use an INNER JOIN. If you need all social_members regardless of whether there is a corresponding social_mcouple then you will need a LEFT JOIN. The LEFT JOIN will give you all rows with social_mcouple.* set to NULL where there is not a match.

The performance hit will really depend on the size of your datasets.

EDIT: adding a sample UNION query.

$res = @mysql_query("
(SELECT social_members.*, social_member_types.*, DATE_FORMAT(m_lld,'%m/%d/%y') AS m_lld_formatted,
  NULL AS mcouple1, NULL AS mcouple2, NULL AS mcouple3
FROM social_members 
LEFT JOIN social_member_types ON t_id=m_type
WHERE m_user='".$en['user']."' AND m_type != 2)

UNION

(SELECT social_members.*, social_member_types.*, DATE_FORMAT(m_lld,'%m/%d/%y') AS m_lld_formatted,
    social_mcouple.mcouple1, social_mcouple.mcouple2, social_mcouple.mcouple3
FROM social_members 
LEFT JOIN social_member_types ON t_id=m_type
     JOIN social_mcouple ON social_members.m_id = social_mcouple.c_id
WHERE m_user='".$en['user']."' AND m_type = 2)
");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜