left join、right join、inner join关联查询时出现重复数据

left join、right join、inner join关联查询时出现重复数据先放一条重复数据的脏SQLSELECTO.IDASID,O.NAMEASNAME,COUNT(C.ID)ASCLASS_NUMFROMT_BASE_ORGANIZATIONOLEFTJOINT_XSXX_CLASSINFORMATIONCONO.ID=C.FACULTY_IDLEFTJOINT_SZDW_CLASSMEETING_PLANPON…

大家好,欢迎来到IT知识分享网。left

先放一条 重复数据 的脏SQL

SELECT O.ID AS ID,O.NAME AS NAME,COUNT(C.ID) AS CLASS_NUM FROM T_BASE_ORGANIZATION O
LEFT JOIN T_XSXX_CLASSINFORMATION C ON O.ID = C.FACULTY_ID
LEFT JOIN T_SZDW_CLASSMEETING_PLAN P ON C.ID = P.CLASS_ID
WHERE C.GRADE = 2010
GROUP BY O.ID,O.NAME,O.ORDERS
ORDER BY O.ORDERS

这表结构是:
T_BASE_ORGANIZATION 学院表
T_XSXX_CLASSINFORMATION 班级表
T_SZDW_CLASSMEETING_PLAN 班会表
一个学院 多个班级
一个班级 多个班会
总之引发查询出重复数据就是因为,表之间关联的关系不是一对一的而是一对多,从而导致数据重复。
解决方式

方法一:在 GROUP BY 加上(多表的外键) C.ID
SELECT O.ID AS ID,O.NAME AS NAME,COUNT(C.ID) AS CLASS_NUM FROM T_BASE_ORGANIZATION O
LEFT JOIN T_XSXX_CLASSINFORMATION C ON O.ID = C.FACULTY_ID
LEFT JOIN T_SZDW_CLASSMEETING_PLAN P ON C.ID = P.CLASS_ID
WHERE C.GRADE = 2010
GROUP BY O.ID,O.NAME,O.ORDERS,C.ID
ORDER BY O.ORDERS

    

方法二:在返回结果数据的 地方加上DISTINCT函数, COUNT(DISTINCT(C.ID))
SELECT O.ID AS ID,O.NAME AS NAME,COUNT(DISTINCT(C.ID)) AS CLASS_NUM FROM T_BASE_ORGANIZATION O
LEFT JOIN T_XSXX_CLASSINFORMATION C ON O.ID = C.FACULTY_ID
LEFT JOIN T_SZDW_CLASSMEETING_PLAN P ON C.ID = P.CLASS_ID
WHERE C.GRADE = 2010
GROUP BY O.ID,O.NAME,O.ORDERS
ORDER BY O.ORDERS



  



方法三:在做left join、right join、inner join的时候将 关联的表先DISTINCT(外键) 子查询一遍    
SELECT O.ID AS ID,O.NAME AS NAME,COUNT(C.ID) AS CLASS_NUM FROM T_BASE_ORGANIZATION O
LEFT JOIN T_XSXX_CLASSINFORMATION C ON O.ID = C.FACULTY_ID
LEFT JOIN (SELECT DISTINCT(Z.CLASS_ID) FROM T_SZDW_CLASSMEETING_PLAN Z ) P ON C.ID = P.CLASS_ID
WHERE C.GRADE = 2010
GROUP BY O.ID,O.NAME,O.ORDERS
ORDER BY O.ORDERS

不推荐 使用方法一
ORDER BY 函数 影响范围广。
推荐使用方法一
子查询 作用范围小,不影响整体SQL。

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/10448.html

(0)

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信