有个问题始终想不通
left join 后应该记录数不变,为什么记录变少了?
select count (*) from product 有 9037条记录
select count (*) from product left join v_inv on product.prod_no=v_inv.prod_no where datediff(day,v_inv.inv_date,getdate())<30 只有 1330条记录?怎样能查到 9037条记录而又可以 关联v_inv?
[解决办法]
select count(*) from
(select * from product left join v_inv on product.prod_no=v_inv.prod_no where datediff(day,v_inv.inv_date,getdate())<30)a
试试
[解决办法]
select count (*) from product left join v_inv on product.prod_no=v_inv.prod_no
where datediff(day,v_inv.inv_date,getdate())<30
where 是连接后筛选符合条件的记录,顺序不一样,可以试试:
select count (*)
from product left join v_inv on product.prod_no=v_inv.prod_no
and datediff(day,v_inv.inv_date,getdate())<30
[解决办法]
where datediff(day,v_inv.inv_date,getdate())<30限制了最终输出条数,如果条件全写在ON里就是只会多不会少。
[解决办法]
select count(*)from product left join ( select prod_no from v_inv where datediff(day, v_inv.inv_date, getdate()) < 30 ) v_inv on product.prod_no = v_inv.prod_no--作一个子查询再连接,就可以了