为什么我的查询没有使用Mysql返回准确的结果

时间:2015-06-07 05:10:29

标签: mysql

我正在使用以下查询从表中获取重复记录。它可以满足上述要求。

select tc_vessel_name, 
count(tc_vessel_name)as Vessel_Name from t_vessel_m as v
group by tc_vessel_name
having Vessel_Name >1

但真正的问题是,当我使用下面的查询来查找在其他表中具有相同id条目的重复结果时,它返回null结果。我无法理解这背后的真正原因。请帮助我。

SELECT  tc_vessel_id,tc_vessel_name, COUNT(tc_vessel_name) AS Vesse_Name
FROM    t_vessel_m
WHERE   tc_vessel_id IN (SELECT tc_vessel_id FROM t_vessel_x) AND 
t_vessel_m.tc_is_deleted='F'
GROUP BY tc_vessel_name
HAVING ( COUNT(tc_vessel_name) > 1 )

1 个答案:

答案 0 :(得分:0)

您在第一次查询中未正确查找重复项。这样:

select tc_vessel_name, 
count(tc_vessel_name)as Vessel_Name from t_vessel_m as v
group by tc_vessel_name
having Vessel_Name > 1

应该是这样的:

select tc_vessel_name, 
count(tc_vessel_name)as Vessel_Name from t_vessel_m as v
group by tc_vessel_name
having count(Vessel_Name) > 1

你真正做的是比较不是群体的数量,而是将分组的价值比作1.因此,第一和第二陈述是不同的。看看这个小提琴http://sqlfiddle.com/#!9/f5895/1没有重复,但结果却得到2行。在Sql Server中,它会为您提供强制转换异常,但它会隐式地将1转换为MySql中的varchar。