MySQL使用左连接计算查询中的行数

MySQL使用左连接计算查询中的行数,mysql,join,count,Mysql,Join,Count,我有一个如下的查询: Select x.date, x.id, x.phone, x.product, xy.policy,xy.date from (y left join z on y.customer_id=z.customer_id) left join x on x.id=z.id left join xy on xy.id=x.id where x.date > '2000-01-01

我有一个如下的查询:

 Select x.date, x.id, x.phone,
    x.product, xy.policy,xy.date 
 from (y left join z 
            on y.customer_id=z.customer_id)
    left join x 
       on x.id=z.id 
    left join xy 
       on xy.id=x.id 
 where x.date > '2000-01-01'  
    and y.detail =foo 
    and xy.policy like 'foo_____'  
    and xy.policy_type = foo;
如何计算此返回的行数

我尝试使用SQL\u CALC\u FOUND\u行,但无法将其完全应用于此查询

任何帮助都将不胜感激

谢谢,
Stefan.

最简单的方法就是添加一个子查询

 Select x.date, x.id, x.phone,
    x.product, xy.policy,xy.date,
    (Select Count(*) 
     From (y left join z on y.customer_id=z.customer_id)
        left join x on x.id=z.id 
        left join xy  on xy.id=x.id 
     where x.date > '2000-01-01'  
       and y.detail =foo 
       and xy.policy like 'foo_____'  
       and xy.policy_type = foo) RecordCount  
 from (y left join z 
            on y.customer_id=z.customer_id)
    left join x 
       on x.id=z.id 
    left join xy 
       on xy.id=x.id 
 where x.date > '2000-01-01'  
    and y.detail =foo 
    and xy.policy like 'foo_____'  
    and xy.policy_type = foo;
如果您只需要计数,那么:

 Select Count(*) 
 From (y left join z on y.customer_id=z.customer_id)
    left join x on x.id=z.id 
    left join xy  on xy.id=x.id 
 where x.date > '2000-01-01'  
   and y.detail =foo 
   and xy.policy like 'foo_____'  
   and xy.policy_type = foo
你可以写:

SELECT COUNT(1)
  FROM y
  JOIN z
    ON y.customer_id = z.customer_id
  JOIN x
    ON x.id = z.id
  JOIN xy
    ON xy.id = x.id
 WHERE x.date > '2000-01-01'
   AND y.detail = foo
   AND xy.policy LIKE 'foo_____'
   AND xy.policy_type = foo
;
(请注意,我已将您的
左连接
s更改为常规
连接
s,因为
WHERE
子句阻止它们实际充当
左连接
s。如果您想要真正的
左连接
s,可以将条件从
WHERE
子句移动到
ON
子句中:

SELECT COUNT(1)
  FROM y
  LEFT
  JOIN z
    ON z.customer_id = y.customer_id
  LEFT
  JOIN x
    ON x.id = z.id
   AND x.date > '2000-01-01'
  LEFT
  JOIN xy
    ON xy.id = x.id
   AND xy.policy LIKE 'foo_____'
   AND xy.policy_type = foo
 WHERE y.detail = foo
;

)

你能概述一下查询并在周围添加一些代码标签吗?你想为结果的总行添加另一列吗?例如
ID,ColA,TotalResult
1,1,4
1,2,4
1,3,4
1,4,4
?不,谢谢,我只想知道这会返回多少。基本上,如果我能包装一个计数()围绕这一点,我会做的。嗨,查尔斯,你的查询返回的是正确的计数,但我想要的只是计数。我不想要表格。我只想要一个数字来计算行数。@StefanHanotin:好的;你理解我关于
左连接
s和
WHERE
子句的解释了吗?我理解你的评论。您的顶部查询按预期工作。不确定为什么底部查询的计数不同。