SQL 2相同的行
我的问题是:SQL 2相同的行,sql,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.
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行-但它们是相同的。为什么我得到两个结果而不是一个?可能在评论或家庭历史记录上存在双重关系,您可以通过返回
*
作为结果来检查。应该在某个地方有所区别
提供完整的结果以发现问题
您可以(但不推荐)通过设置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
当您连接存在一对多关系的表时,您会看到返回了多行,而事实上该行在主表中只存在一次,但在一个子表中有多行相关数据
还要注意,由于子表中没有匹配的记录,因此可能会丢失所需的数据。在这种情况下,请使用。这取决于表的结构和表中的数据。你能在你的问题中添加相关表格结构的描述吗?这是由于JOIN。使用
DISTINCT
关键字获取不同的行。连接中使用的哪些ID保证(而不仅仅是假定的)是唯一的?我认为仅使用DISTINCT不是一个好方法。如果存在重复数据,而您对此无能为力,那么您真的没有选择的余地。但是,如果复制是因为没有正确过滤而发生的,那么使用distinct只会隐藏一个错误,这个错误可能会在将来产生不良后果。