避免多次LEFT JOIN

时间:2010-04-21 16:44:54

标签: php mysql

有没有办法避免为表“social_mcouple”添加第二个LEFT JOIN来查询下面的social_members.m_id = social_mcouple.c_id?

$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']."'");

1 个答案:

答案 0 :(得分:2)

如果始终存在与social_mcouple对应的social_members,或者您只对存在对应关系的行感兴趣,则可以使用INNER JOIN。如果您需要所有social_members,无论是否有相应的social_mcouple,那么您将需要LEFT JOIN。 LEFT JOIN将为您提供social_mcouple.*设置为NULL且不匹配的所有行。

性能影响实际上取决于数据集的大小。

编辑:添加样本UNION查询。

$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)
");