有没有办法避免为表“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']."'");
答案 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)
");