1. 程式人生 > >MySQL語句中 LEFT JOIN 、INNER JOIN 、RIGHT JOIN 區別

MySQL語句中 LEFT JOIN 、INNER JOIN 、RIGHT JOIN 區別

今天遇見一個吭,許是我沒有理解清楚三者之間的聯絡。

不多說,直接上程式碼:

MySQL查詢語句:

SELECT u.* FROM tb_active_user AS u LEFT JOIN tb_active_team AS t ON t.user_id = #{userId} AND t.active_user_id = u.active_user_id AND t.delete_flag = 0 AND u.delete_flag = 0 AND u.active_id = #{activeId}

結果:

org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 4
	at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:77)
	at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:446)
	at com.sun.proxy.$Proxy71.selectOne(Unknown Source)
	at org.mybatis.spring.SqlSessionTemplate.selectOne(SqlSessionTemplate.java:166)
	at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:83)
	at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:59)
	at com.sun.proxy.$Proxy705.getActiveDetails(Unknown Source)
	at com.bicycle.weixin.service.impl.WeiXinUserServiceImpl.getActiveDetails(WeiXinUserServiceImpl.java:265)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	at java.lang.reflect.Method.invoke(Unknown Source)
	at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:197)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
	at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
	at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
	at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
	at com.sun.proxy.$Proxy726.getActiveDetails(Unknown Source)
	at com.bicycle.weixin.controller.UserController.getActiveDetails(UserController.java:523)
	at sun.reflect.NativeMethodA

結果報錯了,意思是查詢出四條資料,但是接受的只有一條。

然後想了想關於 LEFT JOIN 、INNER JOIN 、RIGHT JOIN 三者之間的區別:

INNER JOIN  是內連線,兩張表之間查詢指定欄位

LEFT  JOIN  是左外連結,查詢左邊表的全部資料,也是我剛剛報錯的原因

RIGHT  JOIN  是右外連結,查詢右邊表的全部資料

吃一線,長一智。要不斷的學習,才能減少程式碼錯誤的書寫。