MySQL使用左连接计数来自查询的行

时间:2012-11-20 15:51:28

标签: 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'  
    and y.detail =foo 
    and xy.policy like 'foo_____'  
    and xy.policy_type = foo;

如何计算此返回的行数?

我尝试使用SQL_CALC_FOUND_ROWS,但我不太适合这个查询。

非常感谢任何帮助。

谢谢, 斯蒂芬。

2 个答案:

答案 0 :(得分:1)

最简单的只是添加一个子查询......

 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

答案 1 :(得分:0)

你可以写:

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
;

(请注意,我已经冒昧地将您的LEFT JOIN更改为常规JOIN,因为WHERE条款阻止它们实际运作LEFT JOIN s无论如何。如果你想要真正的LEFT JOIN,你可以将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
;