2012-11-20 46 views
0

我有一个查询,看起来像这样:MySQL的计数行加入

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,但我不能完全适合这个查询。

任何帮助将不胜感激。

谢谢, Stefan。

+0

可以概括查询和周围添加一些代码的标签吗? – Ruben

+0

是否要为结果的总行添加另一列?例如'ID,ColA,TotalResult','1,1,4','1,2,4','1,3,4','1,4,4'? –

+0

不,谢谢,我只想得到这个回报的计数。基本上,如果我可以包裹一个计数(),我会完成。 – StefanHanotin

回答

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的作用。如果你想真正LEFT JOIN 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 
; 

+0

您的查询不会返回正确的行数。 – StefanHanotin

+0

@StefanHanotin:哪一个? – ruakh

+0

最下面一个不正确 – StefanHanotin

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 
+0

嗨查尔斯,你的查询返回正确的数量,但我想要的只是计数。我不想要桌子。我只想要一个数字来计算行数。 – StefanHanotin

+0

然后,只需使用内部子查询..我编辑,以表明这一点。 –