LEFT JOIN个别问题

Posted wutianfei

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LEFT JOIN个别问题相关的知识,希望对你有一定的参考价值。

SELECT
a.loginuser,
a.schoolid,
count(b.id)
FROM
vhs_school AS a
LEFT JOIN vhs_attence AS b ON a.schoolid = b.schoolid
WHERE
b.recordtime > 1546791470
AND b.recordtime < 1546874270
GROUP BY
a.schoolid

SELECT
a.loginuser,
a.schoolid,
count(b.id)
FROM
vhs_school AS a
LEFT JOIN vhs_attence AS b ON a.schoolid = b.schoolid
AND b.recordtime > 1546791470
AND b.recordtime < 1546874270
GROUP BY
a.schoolid

前者就算用了left join 但是结果还是没有显示a表中的所有字段,因为b表的筛选条件放到最外层,这样就相当于将a表关联b表又做了一遍筛选,所有丢失了a表中其他的字段

后者已经筛选b表的数据后,数据量会减少,再去关联a

后者也可以用

SELECT
a.loginuser,
a.schoolid,
count(b.id)
FROM
vhs_school AS a
LEFT JOIN (
SELECT
*
FROM
vhs_attence AS b b.recordtime > 1546791470
AND b.recordtime < 1546874270
) b ON a.schoolid = b.schoolid

以上是关于LEFT JOIN个别问题的主要内容,如果未能解决你的问题,请参考以下文章

关于SQL 查询效率问题 left join 改成 inner join union

SQL语句多表left join SUM出现的重复数据问题!

Hibernate中left join fetch 查询出现重复的对象

SQL Server 中的 LEFT JOIN 与 LEFT OUTER JOIN

left join 如何三表查询

Hibernate 中 LEFT JOIN 和 LEFT JOIN FETCH 的区别?