SQL 2相同的行

时间:2013-03-04 20:43:07

标签: sql

我的查询:

SELECT CONCAT(f.name, ' ', f.parent_names) AS FullName,
       stts.name AS 'Status',
       u.name AS Unit,
       city.name AS City,
       hus.mobile1 AS HusbandPhone,
       wife.mobile1 AS WifePhone,
       f.phone AS HomePhone,
       f.contact_initiation_date AS InitDate,
       fh.created_at AS StatusChangeDate,
       cmt.created_at AS CommentDate,
       cmt.comment AS LastComment
FROM families f
JOIN categories stts ON f.family_status_cat_id = stts.id
JOIN units u ON f.unit_id = u.id
JOIN categories city ON f.main_city_cat_id = city.id
JOIN contacts hus ON f.husband_id = hus.id
JOIN contacts wife ON f.wife_id = wife.id
JOIN comments cmt ON f.id = cmt.commentable_id
AND cmt.created_at =
    (SELECT MAX(created_at)
     FROM comments
     WHERE commentable_id = f.id)
JOIN family_histories fh ON f.id = fh.family_id
AND fh.created_at =
    (SELECT MAX(created_at)
     FROM family_histories
     WHERE family_id = f.id
         AND family_history_cat_id = 1422)
WHERE f.id = 17883

问题:结果是2行 - 但它们是相同的。为什么我得到2个结果,而不仅仅是一个?

2 个答案:

答案 0 :(得分:1)

可能在评论或family_histories上存在双重关系,您可以通过返回*来查看结果。在某处应该有区别。

提供完整的结果以找到问题。

可以(但不推荐)通过设置DISTINCT来解决它。

SELECT DISTINCT CONCAT(f.name, ' ', f.parent_names) AS FullName, stts.name AS 'Status', u.name AS Unit, city.name AS City, hus.mobile1 AS HusbandPhone, wife.mobile1 AS WifePhone, f.phone AS HomePhone, f.contact_initiation_date AS InitDate, fh.created_at AS StatusChangeDate, cmt.created_at AS CommentDate, cmt.comment AS LastComment
FROM families f JOIN categories stts ON f.family_status_cat_id = stts.id
JOIN units u ON f.unit_id = u.id
JOIN categories city ON f.main_city_cat_id = city.id
JOIN contacts hus ON f.husband_id = hus.id
JOIN contacts wife ON f.wife_id = wife.id
JOIN comments cmt ON f.id = cmt.commentable_id AND cmt.created_at = (SELECT MAX(created_at) FROM comments WHERE commentable_id = f.id)
JOIN family_histories fh ON f.id = fh.family_id AND fh.created_at = (SELECT MAX(created_at) FROM family_histories WHERE family_id = f.id AND family_history_cat_id = 1422)
WHERE f.id = 17883

答案 1 :(得分:1)

当您连接具有一对多关系的表时,您将看到返回多行,而实际上该行仅在主表中存在一次,但其中一行中存在多行相关数据儿童表。

另请注意,您期望的数据可能会丢失,因为子表中没有匹配的记录,在这种情况下使用LEFT JOIN