2013-03-04 62 views
0

我的查詢:SQL 2個相同的行

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個結果,而不僅僅是一個?

+1

這取決於您的表格結構和表格中的數據。你可以在你的問題中添加相關表結構的描述嗎? – Melanie 2013-03-04 20:45:05

+1

這是由於JOIN。使用'DISTINCT'關鍵字來獲得不同的行。 – 2013-03-04 20:45:58

+0

JOIN中使用的哪個ID是**保證**(不只是假設)是** unique **? – 2013-03-04 20:47:11

回答

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

這是我的觀點,只是使用獨特不是一個好方法。如果有重複的數據,你無法做任何事情,你沒有選擇。但是,如果因爲您沒有正確過濾而發生重複,則使用不同的視圖會隱藏可能會導致未來不良後果的錯誤。 – invertedSpear 2013-03-04 20:49:22

+0

你是對的! family_histories有2個不同的id。大! – 2013-03-05 12:12:46

1

當您加入表那裏是一個一對多的關係,你會出現獲得多行返回,而事實上該行只在主表中存在一次,但也有相關的多行數據在其中一個子表中。

另外要注意你所期望的數據可能會丟失,因爲沒有在子表中沒有匹配的記錄,在這種情況下使用LEFT JOIN